82 Commits
Author SHA1 Message Date
jay 9971419dc4 chore: release v4.1.5-fork.6
Build / build (push) Successful in 6m10s
Release / release (push) Successful in 7m9s
2026-11-28 16:36:37 -05:00
jay 72bbef3891 Validate deck-shuffle order splice; fall back to full repin 2026-11-28 16:35:37 -05:00
jay 501f8934f0 Add queue drawer deck-shuffle button 2026-11-28 16:17:07 -05:00
jay 6001741e10 Pin deck-shuffle diff behavior to a wholesale Replace 2026-11-28 16:14:19 -05:00
jay 1eb490d209 Add deck shuffle to the playback manager 2026-11-28 16:11:38 -05:00
jay acad21d0bd chore: release v4.1.5-fork.5
Build / build (push) Successful in 1h16m36s
Release / release (push) Successful in 8m29s
2026-11-14 18:57:46 -05:00
jay 23ddfaf48f Fix Taglib generation after clean builds 2026-11-14 13:41:27 -05:00
jay 7d649ad0ae Verify snapshot playback integration 2026-11-14 13:12:11 -05:00
jay e1bc0cd0e1 Publish and capture snapshot libraries during indexing 2026-11-14 12:46:58 -05:00
jay 5df6f9e623 Coordinate snapshot restoration before indexing 2026-11-14 08:50:28 -05:00
jay f79fb30710 Capture and restore complete snapshot libraries 2026-11-14 08:33:32 -05:00
jay 2dc6443798 Validate snapshot configuration fingerprints 2026-11-14 08:24:02 -05:00
jay d3f40eacbf Add atomic library snapshot file store 2026-11-14 08:12:39 -05:00
jay 2ccf885bec Add validated library snapshot documents 2026-11-14 07:50:12 -05:00
jay 31f092f8f4 Restore live playlists in snapshot graphs 2026-11-14 07:29:26 -05:00
jay a46849c1ac Rebuild library graphs from snapshot songs 2026-11-14 07:08:20 -05:00
jay 6b9cd62c52 Add library snapshot song record codec 2026-11-14 06:59:58 -05:00
jay 690672a887 Add no-I/O library snapshot cover restoration 2026-11-14 06:32:00 -05:00
jay 34df60ba2e Add library snapshot name codec 2026-11-14 06:18:16 -05:00
jay f3cfa995c3 Add file and volume snapshot codecs 2026-11-14 06:06:05 -05:00
jay b380a412d2 Add domain library snapshot codecs 2026-11-14 05:05:50 -05:00
jay 9d75890ae7 Add primitive library snapshot codecs 2026-11-14 04:54:20 -05:00
jay 7a72c6163f Harden library snapshot string decoding 2026-11-14 04:44:16 -05:00
jay 51b8ee9b9a Add bounded library snapshot strings 2026-11-13 21:02:19 -05:00
jay 86eb441d33 Test truncated library snapshot headers 2026-11-13 20:57:37 -05:00
jay 17172705b4 Reject unsupported library snapshot versions 2026-11-13 20:54:40 -05:00
jay 32c037f58d Reject invalid library snapshot magic 2026-11-13 20:52:57 -05:00
jay 8d29fd9038 Add library snapshot header codec 2026-11-13 20:50:47 -05:00
jay cc88b1e7eb Revert "perf: move indexing relays off main thread"
This reverts commit af4829f32a.
2026-11-13 18:24:48 -05:00
jay af4829f32a perf: move indexing relays off main thread 2026-11-13 18:17:16 -05:00
jay d2e9eacc03 perf: avoid locking initialized cache-map reads 2026-11-13 18:05:22 -05:00
jay 858174e695 Revert "perf: reuse successful cover lookups per index"
This reverts commit 81dee79230.
2026-11-13 17:58:13 -05:00
jay b60084216c Revert "test: cover cached cover miss retry"
This reverts commit 932390e568.
2026-11-13 17:58:13 -05:00
jay 932390e568 test: cover cached cover miss retry 2026-11-13 17:47:28 -05:00
jay 81dee79230 perf: reuse successful cover lookups per index 2026-11-13 15:24:00 -05:00
jay 2f4b600a0a test: cover terminal indexing progress ordering 2026-11-13 14:48:37 -05:00
jay 23419cc35e perf: coalesce indexing progress updates 2026-11-13 14:46:44 -05:00
jay bb0d0ebbde perf: reuse Any-Latin transliterators per thread 2026-11-13 14:23:20 -05:00
jay 214054c5e4 perf: memoize intelligent name tokens per index 2026-11-13 14:10:20 -05:00
jay e12f00c49b chore: release v4.1.5-fork.4
Build / build (push) Successful in 6m19s
Release / release (push) Successful in 6m49s
2026-11-12 19:31:58 -05:00
jay 66947b80bc musikr: parse APE tags on mpeg files, log ReplayGain values in debug 2026-11-12 19:27:33 -05:00
jay 208e48a97b musikr: read ReplayGain with APE preferred over ID3v2 2026-11-12 19:24:56 -05:00
jay 65bfdf6b7d musikr: import and track discovered playlists during indexing 2026-11-12 18:54:33 -05:00
jay f492410484 musikr: never reconcile destructively 2026-11-12 18:48:03 -05:00
jay 39deae7644 musikr: buffer discovered playlist files during exploration 2026-11-12 18:40:40 -05:00
jay 38bd9cd260 musikr: track playlist source files in the database 2026-11-12 18:26:13 -05:00
jay ecd71d2699 musikr: create tracked playlists for newly discovered files 2026-11-12 18:22:22 -05:00
jay 366945499e musikr: reconcile tracked playlists against discovered files 2026-11-12 18:20:54 -05:00
jay 843bf55fd1 musikr: pin playlist-name parsing 2026-11-12 18:18:25 -05:00
jay e4cca068db musikr: resolve playlist imports by probe-and-lock 2026-11-12 18:17:03 -05:00
jay a9f6c82041 musikr: pin null when no playlist entry resolves 2026-11-12 18:05:43 -05:00
jay e4d4da371d musikr: pin probe advancement past a missing first entry 2026-11-12 18:04:02 -05:00
jay ac0966c8ea musikr: pin survivor resolution when playlist entries are missing 2026-11-12 18:02:25 -05:00
jay 960061e615 musikr: strip leading segments when probing absolute playlist entries 2026-11-12 18:01:38 -05:00
jay 3387ccedaf musikr: pin root order as precedence in playlist resolution 2026-11-12 18:00:15 -05:00
jay 18fde00a41 musikr: pin dotdot resolution of playlist entries 2026-11-12 17:58:58 -05:00
jay e206acde3f musikr: normalize dot segments when resolving playlist entries 2026-11-12 17:57:37 -05:00
jay 7ad4fe5f8c musikr: resolve playlist entries by probe-and-lock against candidate roots 2026-11-12 17:56:13 -05:00
jay 442a066136 chore: release v4.1.5-fork.3
Build / build (push) Successful in 5m42s
Release / release (push) Successful in 6m41s
2026-11-12 16:57:53 -05:00
jay 1f3e319552 list: let the swipe reveal stretch to three cell widths 2026-11-12 16:52:51 -05:00
jay 7efa7bff59 list: keep the swipe underlay visible through the spring-back 2026-11-12 16:50:07 -05:00
jay 037c5b1382 list: commit swipes on spring-back instead of flying off 2026-11-12 16:48:02 -05:00
jay 93c8f8f05f list: zero change-animation duration on swipeable lists instead 2026-11-12 16:44:06 -05:00
jay a251d5fc2d list: disable change cross-fades on swipeable lists 2026-11-12 16:39:27 -05:00
jay 9f2b8894df list: restore swipe recovery by dropping the payload rebind 2026-11-12 16:36:43 -05:00
jay 18332d8478 list: rubber-band the swipe reveal, mute swipes while playlist-editing 2026-11-12 16:32:39 -05:00
jay 94170a8079 list: square swipe reveal with resistance, Lucide action icons 2026-11-12 16:21:35 -05:00
jay a1615f3c1b list: swipe song rows right to queue, left to play next 2026-11-12 16:08:59 -05:00
jay f1e999effc queue: pad the sheet's below-screen overflow so the empty hint centers 2026-11-12 15:58:19 -05:00
jay 9c6380489c queue: hide the drag handle on the playing row 2026-11-12 15:52:20 -05:00
jay 1b5134f854 playback: never lose pager commands to event overwrite 2026-11-12 15:43:43 -05:00
jay 642a3add27 playback: instrument the cover pager's command path 2026-11-12 15:33:45 -05:00
jay 6e2a260df9 queue: update the drawer with precise per-change instructions 2026-11-12 15:32:04 -05:00
jay 0d6a3240ad playback: navigate to the parent deterministically from the header 2026-11-12 14:58:44 -05:00
jay 23135fe80d playback: notify listeners only after deck bookkeeping settles 2026-11-12 14:55:17 -05:00
jay a8e898d5e9 playback: navigate via the now-playing header tap 2026-11-12 14:51:20 -05:00
jay c784b4cebd queue: render the deck only, with clear button and Now Playing header 2026-11-12 13:54:55 -05:00
jay ecc6f34a02 playback: publish the deck to the queue drawer 2026-11-12 13:40:00 -05:00
jay b7c425b410 playback: add moveDeckItems for queue-drawer drags 2026-11-12 13:34:34 -05:00
jay 7c130ac6c3 playback: add removeDeckItem for queue-drawer swipes 2026-11-12 13:31:53 -05:00
jay d17f789dd2 playback: add gotoDeck for queue-drawer taps 2026-11-12 13:28:48 -05:00
jay a19bfbaddf playback: add clearQueue for the drawer's clear button 2026-11-12 13:11:01 -05:00
95 changed files with 7645 additions and 416 deletions
+4 -2
View File
@@ -16,8 +16,8 @@ android {
defaultConfig { defaultConfig {
applicationId namespace applicationId namespace
versionName "4.1.5-fork.2" versionName "4.1.5-fork.6"
versionCode 77 versionCode 81
minSdk min_sdk minSdk min_sdk
// randomly flickers between deprecated and required depending on what mood my gradle is in // randomly flickers between deprecated and required depending on what mood my gradle is in
@@ -93,6 +93,8 @@ kotlin {
dependencies { dependencies {
testImplementation "junit:junit:4.13.2" testImplementation "junit:junit:4.13.2"
testImplementation "io.mockk:mockk:1.14.11"
testImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:$kotlin_coroutines_version"
androidTestImplementation "androidx.test:runner:1.7.0" androidTestImplementation "androidx.test:runner:1.7.0"
androidTestImplementation "androidx.test.ext:junit:1.3.0" androidTestImplementation "androidx.test.ext:junit:1.3.0"
@@ -29,6 +29,7 @@ import androidx.core.view.ViewCompat
import androidx.core.view.isInvisible import androidx.core.view.isInvisible
import androidx.core.view.isVisible import androidx.core.view.isVisible
import androidx.fragment.app.activityViewModels import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.findNavController import androidx.navigation.findNavController
import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.findNavController
import com.google.android.material.R as MR import com.google.android.material.R as MR
@@ -57,6 +58,7 @@ import org.oxycblt.auxio.playback.OpenPanel
import org.oxycblt.auxio.playback.PlaybackBottomSheetBehavior import org.oxycblt.auxio.playback.PlaybackBottomSheetBehavior
import org.oxycblt.auxio.playback.PlaybackViewModel import org.oxycblt.auxio.playback.PlaybackViewModel
import org.oxycblt.auxio.playback.queue.QueueBottomSheetBehavior import org.oxycblt.auxio.playback.queue.QueueBottomSheetBehavior
import org.oxycblt.auxio.playback.queue.QueueViewModel
import org.oxycblt.auxio.ui.DialogAwareNavigationListener import org.oxycblt.auxio.ui.DialogAwareNavigationListener
import org.oxycblt.auxio.ui.UISettings import org.oxycblt.auxio.ui.UISettings
import org.oxycblt.auxio.ui.ViewBindingFragment import org.oxycblt.auxio.ui.ViewBindingFragment
@@ -71,6 +73,11 @@ import org.oxycblt.auxio.util.navigateSafe
import org.oxycblt.auxio.util.unlikelyToBeNull import org.oxycblt.auxio.util.unlikelyToBeNull
import org.oxycblt.musikr.Music import org.oxycblt.musikr.Music
import org.oxycblt.musikr.Song import org.oxycblt.musikr.Song
import org.oxycblt.musikr.Album
import org.oxycblt.musikr.Artist
import org.oxycblt.musikr.Genre
import org.oxycblt.musikr.MusicParent
import org.oxycblt.musikr.Playlist
import timber.log.Timber as L import timber.log.Timber as L
/** /**
@@ -88,6 +95,7 @@ class MainFragment :
private val homeModel: HomeViewModel by activityViewModels() private val homeModel: HomeViewModel by activityViewModels()
private val listModel: ListViewModel by activityViewModels() private val listModel: ListViewModel by activityViewModels()
private val playbackModel: PlaybackViewModel by activityViewModels() private val playbackModel: PlaybackViewModel by activityViewModels()
private val queueModel: QueueViewModel by activityViewModels()
private var sheetBackCallback: SheetBackPressedCallback? = null private var sheetBackCallback: SheetBackPressedCallback? = null
private var detailBackCallback: DetailBackPressedCallback? = null private var detailBackCallback: DetailBackPressedCallback? = null
private var selectionBackCallback: SelectionBackPressedCallback? = null private var selectionBackCallback: SelectionBackPressedCallback? = null
@@ -121,6 +129,10 @@ class MainFragment :
binding.queueSheet.coordinatorLayoutBehavior as QueueBottomSheetBehavior? binding.queueSheet.coordinatorLayoutBehavior as QueueBottomSheetBehavior?
queueSheetBehavior?.uiSettings = uiSettings queueSheetBehavior?.uiSettings = uiSettings
// --- QUEUE SHEET SETUP ---
binding.queueClear.setOnClickListener { queueModel.clearQueue() }
binding.queueShuffle.setOnClickListener { queueModel.shuffleDeck() }
elevationNormal = binding.context.getDimen(MR.dimen.m3_sys_elevation_level1) elevationNormal = binding.context.getDimen(MR.dimen.m3_sys_elevation_level1)
// Currently all back press callbacks are handled in MainFragment, as it's not guaranteed // Currently all back press callbacks are handled in MainFragment, as it's not guaranteed
@@ -214,6 +226,7 @@ class MainFragment :
// FIXME: This is a consequence of sharing events across several consumers. There has to be // FIXME: This is a consequence of sharing events across several consumers. There has to be
// a better way of doing this. // a better way of doing this.
collect(detailModel.toShow.flow, ::handleShow) collect(detailModel.toShow.flow, ::handleShow)
collect(playbackModel.parentNavigation.flow, ::handleParentNavigation)
collectImmediately(detailModel.editedPlaylist, detailBackCallback::invalidateEnabled) collectImmediately(detailModel.editedPlaylist, detailBackCallback::invalidateEnabled)
collectImmediately(homeModel.showOuter.flow, ::handleShowOuter) collectImmediately(homeModel.showOuter.flow, ::handleShowOuter)
collectImmediately(homeModel.currentTabType, ::updateCurrentTab) collectImmediately(homeModel.currentTabType, ::updateCurrentTab)
@@ -222,6 +235,7 @@ class MainFragment :
collectImmediately(listModel.selected, selectionBackCallback::invalidateEnabled) collectImmediately(listModel.selected, selectionBackCallback::invalidateEnabled)
collectImmediately(playbackModel.song, ::updateSong) collectImmediately(playbackModel.song, ::updateSong)
collectImmediately(playbackModel.openPanel.flow, ::handlePanel) collectImmediately(playbackModel.openPanel.flow, ::handlePanel)
collectImmediately(queueModel.queue, ::updateQueueButtons)
} }
override fun onStart() { override fun onStart() {
@@ -555,6 +569,25 @@ class MainFragment :
binding.sheetScrim.isInvisible = !open binding.sheetScrim.isInvisible = !open
} }
private fun handleParentNavigation(parent: MusicParent?) {
parent ?: return
L.d("Navigating to parent $parent")
playbackModel.parentNavigation.consume()
val navController =
(childFragmentManager.findFragmentById(R.id.explore_nav_host) as NavHostFragment)
.navController
// Root-level actions: the header tap must work no matter which page is in front.
when (parent) {
is Album -> navController.navigateSafe(InnerDirections.showAlbumGlobally(parent.uid))
is Artist -> navController.navigateSafe(InnerDirections.showArtistGlobally(parent.uid))
is Genre -> navController.navigateSafe(InnerDirections.showGenreGlobally(parent.uid))
is Playlist ->
navController.navigateSafe(InnerDirections.showPlaylistGlobally(parent.uid))
else -> return
}
tryClosePlaybackPanel()
}
private fun handleShow(show: Show?) { private fun handleShow(show: Show?) {
when (show) { when (show) {
is Show.SongAlbumDetails, is Show.SongAlbumDetails,
@@ -624,6 +657,13 @@ class MainFragment :
} }
} }
private fun updateQueueButtons(queue: List<Song>) {
requireBinding().queueClear.isVisible = queue.isNotEmpty()
// Shuffling fewer than two waiting entries cannot change anything.
val waiting = queue.size - if (queueModel.index.value == 0) 1 else 0
requireBinding().queueShuffle.isVisible = waiting >= 2
}
private fun tryClosePlaybackPanel() { private fun tryClosePlaybackPanel() {
val binding = requireBinding() val binding = requireBinding()
val playbackSheetBehavior = val playbackSheetBehavior =
@@ -25,6 +25,7 @@ import android.view.View
import androidx.core.view.updatePadding import androidx.core.view.updatePadding
import androidx.fragment.app.activityViewModels import androidx.fragment.app.activityViewModels
import androidx.navigation.findNavController import androidx.navigation.findNavController
import androidx.recyclerview.widget.ItemTouchHelper
import com.google.android.material.appbar.AppBarLayout import com.google.android.material.appbar.AppBarLayout
import com.google.android.material.transition.MaterialSharedAxis import com.google.android.material.transition.MaterialSharedAxis
import kotlin.math.abs import kotlin.math.abs
@@ -36,6 +37,7 @@ import org.oxycblt.auxio.databinding.FragmentDetailBinding
import org.oxycblt.auxio.detail.list.DetailListAdapter import org.oxycblt.auxio.detail.list.DetailListAdapter
import org.oxycblt.auxio.list.ListFragment import org.oxycblt.auxio.list.ListFragment
import org.oxycblt.auxio.list.ListViewModel import org.oxycblt.auxio.list.ListViewModel
import org.oxycblt.auxio.list.recycler.SwipeActionsCallback
import org.oxycblt.auxio.music.MusicViewModel import org.oxycblt.auxio.music.MusicViewModel
import org.oxycblt.auxio.playback.PlaybackViewModel import org.oxycblt.auxio.playback.PlaybackViewModel
import org.oxycblt.auxio.util.getDimenPixels import org.oxycblt.auxio.util.getDimenPixels
@@ -122,6 +124,24 @@ abstract class DetailFragment<P : MusicParent, C : Music> :
binding.detailRecycler.apply { adapter = getDetailListAdapter() } binding.detailRecycler.apply { adapter = getDetailListAdapter() }
ItemTouchHelper(
SwipeActionsCallback(
// Queue swipes are inert during multi-select and while a playlist is being
// edited (the editing gestures — reorder, remove — own the rows then).
isEnabled = {
listModel.selected.value.isEmpty() &&
detailModel.editedPlaylist.value == null
}
) { song,
action ->
when (action) {
SwipeActionsCallback.SwipeAction.QUEUE -> playbackModel.addToQueue(song)
SwipeActionsCallback.SwipeAction.PLAY_NEXT -> playbackModel.playNext(song)
}
}
)
.attachToRecyclerView(binding.detailRecycler)
spacingSmall = requireContext().getDimenPixels(R.dimen.spacing_small) spacingSmall = requireContext().getDimenPixels(R.dimen.spacing_small)
} }
@@ -0,0 +1,241 @@
/*
* Copyright (c) 2026 Auxio Project
* SwipeActionsCallback.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.list.recycler
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.RectF
import android.graphics.drawable.Drawable
import androidx.appcompat.content.res.AppCompatResources
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.R as MR
import kotlin.math.abs
import kotlin.math.min
import kotlin.math.sign
import org.oxycblt.auxio.R
import org.oxycblt.auxio.list.adapter.FlexibleListAdapter
import org.oxycblt.auxio.util.getAttrColorCompat
import org.oxycblt.auxio.util.getDimenPixels
import org.oxycblt.musikr.Song
/**
* An [ItemTouchHelper.Callback] giving song rows swipe actions: swipe-right queues the song at
* the back of the deck, swipe-left plays it next at the deck's front. The row slides freely up
* to a square underlay cell revealing the action's icon, rubber-bands past it, and on release
* always springs back home — every release takes the touch helper's cancel animation, which is
* that spring-back. Committing is tracked here: armed when the finger passes the cell, disarmed
* when pulled back, fired as the row settles ([clearView]).
*
* @param isEnabled Whether swipes are currently allowed (false during multi-select).
* @param onAction Called with the swiped [Song] and the committed [SwipeAction].
* @author OxygenCobalt (Fork)
*/
class SwipeActionsCallback(
private val isEnabled: () -> Boolean,
private val onAction: (Song, SwipeAction) -> Unit,
) : ItemTouchHelper.Callback() {
/** The action committed by a swipe. */
enum class SwipeAction {
/** Swipe-right: queue the song at the back of the deck. */
QUEUE,
/** Swipe-left: play the song next at the deck's front. */
PLAY_NEXT,
}
private val paint = Paint().apply { isAntiAlias = true }
private var queueIcon: Drawable? = null
private var playNextIcon: Drawable? = null
private var armedViewHolder: RecyclerView.ViewHolder? = null
private var armedAction: SwipeAction? = null
override fun getMovementFlags(
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder,
): Int {
if (!isEnabled()) {
return 0
}
// Gate on the item, not the ViewHolder: detail pages use their own row types.
val position = viewHolder.bindingAdapterPosition
if (position == RecyclerView.NO_POSITION) {
return 0
}
val item = (recyclerView.adapter as? FlexibleListAdapter<*, *>)?.getItem(position)
return if (item is Song) {
makeMovementFlags(0, ItemTouchHelper.START or ItemTouchHelper.END)
} else {
0
}
}
override fun onMove(
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder,
target: RecyclerView.ViewHolder,
) = false
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
// Never fires: releases always take the cancel path (see getSwipeThreshold), so the row
// springs back instead of flying off, and commits are handled in clearView.
}
/** Never auto-commit: the release always springs back, and we track commits ourselves. */
override fun getSwipeThreshold(viewHolder: RecyclerView.ViewHolder) = 2f
/** Fling-to-commit would fly the row off-screen; disable it for a consistent spring-back. */
override fun getSwipeEscapeVelocity(defaultValue: Float) = Float.MAX_VALUE
override fun getSwipeVelocityThreshold(defaultValue: Float) = Float.MAX_VALUE
override fun onChildDraw(
c: Canvas,
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder,
dX: Float,
dY: Float,
actionState: Int,
isCurrentlyActive: Boolean,
) {
// Free slide up to the square cell, then rubber-band resistance past it.
val clampedDX =
if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) {
rubberBand(dX, revealWidth(viewHolder).toFloat())
} else {
dX
}
if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) {
if (isCurrentlyActive) {
// Arm when the finger passes the cell; disarm when pulled back inside it.
val raw = abs(dX)
val reveal = revealWidth(viewHolder).toFloat()
if (raw > reveal) {
armedViewHolder = viewHolder
armedAction = if (dX > 0) SwipeAction.QUEUE else SwipeAction.PLAY_NEXT
} else if (raw < reveal * 0.5f) {
armedViewHolder = null
armedAction = null
}
}
// Draw whenever the row is displaced, including the spring-back's frames.
if (clampedDX != 0f) {
drawUnderlay(c, viewHolder, clampedDX)
}
}
super.onChildDraw(c, recyclerView, viewHolder, clampedDX, dY, actionState, isCurrentlyActive)
}
override fun clearView(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder) {
super.clearView(recyclerView, viewHolder)
// The row has settled home; commit if this gesture armed an action.
if (armedViewHolder === viewHolder) {
val action = armedAction
armedViewHolder = null
armedAction = null
if (action != null) {
val position = viewHolder.bindingAdapterPosition
val song =
(recyclerView.adapter as? FlexibleListAdapter<*, *>)?.getItem(position)
as? Song
if (song != null) {
onAction(song, action)
}
}
}
}
/**
* Map a raw drag to its visual translation: one-to-one up to [reveal], then increasing
* resistance asymptotic to three times the reveal, so the row can be pulled well past the
* cell but fights back more the further it goes.
*/
private fun rubberBand(dX: Float, reveal: Float): Float {
val past = abs(dX) - reveal
if (past <= 0f) {
return dX
}
return sign(dX) * (reveal + past / (1f + past / (2f * reveal)))
}
/** The square underlay cell's width: a standard large touchable size. */
private fun revealWidth(viewHolder: RecyclerView.ViewHolder) =
viewHolder.itemView.context.getDimenPixels(R.dimen.size_touchable_large)
/** Draw the revealed action underlay behind the sliding row. */
private fun drawUnderlay(c: Canvas, viewHolder: RecyclerView.ViewHolder, dX: Float) {
val view = viewHolder.itemView
val context = view.context
val reveal = revealWidth(viewHolder).toFloat()
val swipingEnd = dX > 0
val containerAttr: Int
val onContainerAttr: Int
val icon: Drawable
if (swipingEnd) {
containerAttr = MR.attr.colorTertiaryContainer
onContainerAttr = MR.attr.colorOnTertiaryContainer
icon =
queueIcon
?: AppCompatResources.getDrawable(context, R.drawable.ic_queue_add_24)!!.also {
queueIcon = it
}
} else {
containerAttr = MR.attr.colorPrimaryContainer
onContainerAttr = MR.attr.colorOnPrimaryContainer
icon =
playNextIcon
?: AppCompatResources.getDrawable(context, R.drawable.ic_play_next_24)!!.also {
playNextIcon = it
}
}
paint.color = context.getAttrColorCompat(containerAttr).defaultColor
val top = view.top.toFloat()
val bottom = view.bottom.toFloat()
val strip =
if (swipingEnd) {
RectF(view.left.toFloat(), top, view.left + dX, bottom)
} else {
RectF(view.right + dX, top, view.right.toFloat(), bottom)
}
c.drawRect(strip, paint)
// The icon sits centered in the square cell, fading in as the cell is revealed.
val size = context.getDimenPixels(R.dimen.size_icon_medium).toFloat()
icon.setTintList(context.getAttrColorCompat(onContainerAttr))
icon.alpha = (255 * min(strip.width(), reveal) / reveal).toInt()
val centerY = (top + bottom) / 2
val centerX =
if (swipingEnd) {
view.left + reveal / 2
} else {
view.right - reveal / 2
}
icon.setBounds(
(centerX - size / 2).toInt(),
(centerY - size / 2).toInt(),
(centerX + size / 2).toInt(),
(centerY + size / 2).toInt(),
)
icon.draw(c)
}
}
@@ -0,0 +1,144 @@
/*
* Copyright (c) 2026 Auxio Project
* LibrarySnapshotRestore.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.music
import android.content.Context
import java.io.File
import javax.inject.Inject
import org.oxycblt.musikr.Config
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.CancellationException
import org.oxycblt.auxio.image.ImageSettings
import org.oxycblt.auxio.music.locations.LocationMode
import org.oxycblt.musikr.Interpretation
import org.oxycblt.musikr.Library
import org.oxycblt.musikr.MutableLibrary
import org.oxycblt.musikr.fs.mediastore.MediaStore.FilterMode
import org.oxycblt.musikr.playlist.db.StoredPlaylists
import org.oxycblt.musikr.snapshot.LibrarySnapshot
import org.oxycblt.musikr.snapshot.LibrarySnapshotFingerprint
import org.oxycblt.musikr.snapshot.LibrarySnapshotStore
import org.oxycblt.musikr.tag.interpret.Naming
import org.oxycblt.musikr.tag.interpret.Separators
interface SnapshotRestoration {
suspend fun await(): MutableLibrary?
}
class SharedSnapshotRestoration
internal constructor(
scope: CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.IO),
restore: suspend () -> MutableLibrary?,
) : SnapshotRestoration {
private val deferred = scope.async { restore() }
override suspend fun await(): MutableLibrary? {
return try {
deferred.await()
} catch (exception: CancellationException) {
throw exception
} catch (exception: Exception) {
null
}
}
}
interface SnapshotRestorer {
fun start(): SnapshotRestoration
suspend fun capture(library: Library, config: Config) {}
}
class MusikrSnapshotRestorer
@Inject
constructor(
@dagger.hilt.android.qualifiers.ApplicationContext private val context: Context,
private val storedPlaylists: StoredPlaylists,
private val musicSettings: MusicSettings,
private val imageSettings: ImageSettings,
) : SnapshotRestorer {
override fun start(): SnapshotRestoration {
val interpretation =
Interpretation(
if (musicSettings.intelligentSorting) Naming.intelligent() else Naming.simple(),
Separators.from(musicSettings.separators),
)
val fingerprint = fingerprint()
return SharedSnapshotRestoration {
LibrarySnapshot(context, storedPlaylists, interpretation)
.restore(LibrarySnapshotStore(context.filesDir), fingerprint)
}
}
override suspend fun capture(library: Library, config: Config) {
LibrarySnapshot(context, config)
.capture(
library,
LibrarySnapshotStore(context.filesDir),
fingerprint(),
)
}
private fun fingerprint(): LibrarySnapshotFingerprint {
val sourceMode = musicSettings.locationMode
val sourceRoots: List<String>
val excludedRoots: List<String>
val withHidden: Boolean
val excludeNonMusic: Boolean
when (sourceMode) {
LocationMode.SAF -> {
val query = musicSettings.safQuery
sourceRoots = query.source.map { it.uri.toString() }
excludedRoots = query.exclude.map { it.uri.toString() }
withHidden = query.withHidden
excludeNonMusic = false
}
LocationMode.MEDIA_STORE -> {
val query = musicSettings.mediaStoreQuery
sourceRoots =
if (query.mode == FilterMode.INCLUDE) {
query.filtered.map { it.uri.toString() }
} else {
emptyList()
}
excludedRoots =
if (query.mode == FilterMode.EXCLUDE) {
query.filtered.map { it.uri.toString() }
} else {
emptyList()
}
withHidden = false
excludeNonMusic = query.excludeNonMusic
}
}
return LibrarySnapshotFingerprint(
sourceMode = sourceMode.name,
sourceRoots = sourceRoots,
excludedRoots = excludedRoots,
withHidden = withHidden,
excludeNonMusic = excludeNonMusic,
intelligentSorting = musicSettings.intelligentSorting,
separators = musicSettings.separators,
coverMode = imageSettings.coverMode.name,
)
}
}
@@ -30,4 +30,6 @@ interface MusicModule {
@Singleton @Binds fun repository(musicRepository: MusicRepositoryImpl): MusicRepository @Singleton @Binds fun repository(musicRepository: MusicRepositoryImpl): MusicRepository
@Binds fun settings(musicSettingsImpl: MusicSettingsImpl): MusicSettings @Binds fun settings(musicSettingsImpl: MusicSettingsImpl): MusicSettings
@Binds fun snapshotRestorer(restorer: MusikrSnapshotRestorer): SnapshotRestorer
} }
@@ -23,6 +23,7 @@ import dagger.hilt.android.qualifiers.ApplicationContext
import java.util.UUID import java.util.UUID
import javax.inject.Inject import javax.inject.Inject
import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CancellationException
import org.oxycblt.auxio.BuildConfig
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job import kotlinx.coroutines.Job
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
@@ -245,6 +246,7 @@ constructor(
private val storedPlaylists: StoredPlaylists, private val storedPlaylists: StoredPlaylists,
private val settingCovers: SettingCovers, private val settingCovers: SettingCovers,
private val musicSettings: MusicSettings, private val musicSettings: MusicSettings,
private val snapshotRestorer: SnapshotRestorer,
) : MusicRepository { ) : MusicRepository {
private val updateListeners = mutableListOf<MusicRepository.UpdateListener>() private val updateListeners = mutableListOf<MusicRepository.UpdateListener>()
private val indexingListeners = mutableListOf<MusicRepository.IndexingListener>() private val indexingListeners = mutableListOf<MusicRepository.IndexingListener>()
@@ -256,6 +258,8 @@ constructor(
override val indexingState: IndexingState? override val indexingState: IndexingState?
get() = currentIndexingState ?: previousCompletedState get() = currentIndexingState ?: previousCompletedState
private val snapshotRestoration = snapshotRestorer.start()
@Synchronized @Synchronized
override fun addUpdateListener(listener: MusicRepository.UpdateListener) { override fun addUpdateListener(listener: MusicRepository.UpdateListener) {
L.d("Adding $listener to update listeners") L.d("Adding $listener to update listeners")
@@ -381,6 +385,10 @@ constructor(
private suspend fun indexImpl(withCache: Boolean) { private suspend fun indexImpl(withCache: Boolean) {
L.d("Index requested, initializing") L.d("Index requested, initializing")
val snapshot = snapshotRestoration.await()
if (snapshot != null && !snapshot.empty()) {
emitLibrary(snapshot)
}
// Obtain configuration information // Obtain configuration information
val separators = Separators.from(musicSettings.separators) val separators = Separators.from(musicSettings.separators)
L.d("Separators: $separators") L.d("Separators: $separators")
@@ -411,6 +419,15 @@ constructor(
val start = System.currentTimeMillis() val start = System.currentTimeMillis()
val result = Musikr.new(context, config).run(::emitIndexingProgress) val result = Musikr.new(context, config).run(::emitIndexingProgress)
L.d("Index finished in ${System.currentTimeMillis() - start}ms") L.d("Index finished in ${System.currentTimeMillis() - start}ms")
if (BuildConfig.DEBUG) {
// Surface parsed ReplayGain values for logcat verification.
for (song in result.library.songs) {
val rg = song.replayGainAdjustment
if (rg.track != null || rg.album != null) {
L.d("RG: ${song.name.raw} track=${rg.track} album=${rg.album}")
}
}
}
// Music loading completed, update the revision right now so we re-use this work // Music loading completed, update the revision right now so we re-use this work
// later. // later.
L.d("Revisioning from $currentRevision -> $newRevision") L.d("Revisioning from $currentRevision -> $newRevision")
@@ -423,6 +440,13 @@ constructor(
// Clean up old data that is now impossible for the app to be using. // Clean up old data that is now impossible for the app to be using.
L.d("Cleanup") L.d("Cleanup")
result.cleanup() result.cleanup()
try {
snapshotRestorer.capture(result.library, config)
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
L.w(e, "Library snapshot capture failed")
}
// Finish up loading. // Finish up loading.
L.d("Indexing complete") L.d("Indexing complete")
emitIndexingCompletion(null) emitIndexingCompletion(null)
@@ -53,6 +53,7 @@ class MusicViewModel
constructor( constructor(
@ApplicationContext context: Context, @ApplicationContext context: Context,
private val listSettings: ListSettings, private val listSettings: ListSettings,
private val musicSettings: MusicSettings,
private val musicRepository: MusicRepository, private val musicRepository: MusicRepository,
) : ViewModel(), MusicRepository.UpdateListener, MusicRepository.IndexingListener { ) : ViewModel(), MusicRepository.UpdateListener, MusicRepository.IndexingListener {
private val externalPlaylistManager = ExternalPlaylistManager.from(context) private val externalPlaylistManager = ExternalPlaylistManager.from(context)
@@ -160,24 +161,19 @@ constructor(
fun importPlaylist(uri: Uri? = null, target: Playlist? = null) { fun importPlaylist(uri: Uri? = null, target: Playlist? = null) {
if (uri != null) { if (uri != null) {
viewModelScope.launch(Dispatchers.IO) { viewModelScope.launch(Dispatchers.IO) {
val importedPlaylist = externalPlaylistManager.import(uri) val library = musicRepository.library ?: return@launch
val importedPlaylist =
externalPlaylistManager.import(
uri,
musicSettings.safQuery.source.map { it.path },
library,
)
if (importedPlaylist == null) { if (importedPlaylist == null) {
L.e("Could not import playlist") L.e("Could not import playlist")
playlistMessage.put(PlaylistMessage.ImportFailed) playlistMessage.put(PlaylistMessage.ImportFailed)
return@launch return@launch
} }
val songs = importedPlaylist.songs
val library = musicRepository.library ?: return@launch
val songs =
importedPlaylist.paths.mapNotNull {
it.firstNotNullOfOrNull(library::findSongByPath)
}
if (songs.isEmpty()) {
L.e("No songs found")
playlistMessage.put(PlaylistMessage.ImportFailed)
return@launch
}
if (target !== null) { if (target !== null) {
if (importedPlaylist.name != null && importedPlaylist.name != target.name.raw) { if (importedPlaylist.name != null && importedPlaylist.name != target.name.raw) {
@@ -35,6 +35,7 @@ import org.oxycblt.auxio.music.MusicSettings
import org.oxycblt.auxio.music.locations.LocationMode import org.oxycblt.auxio.music.locations.LocationMode
import org.oxycblt.auxio.playback.state.PlaybackStateManager import org.oxycblt.auxio.playback.state.PlaybackStateManager
import org.oxycblt.auxio.util.getSystemServiceCompat import org.oxycblt.auxio.util.getSystemServiceCompat
import org.oxycblt.musikr.Library
import org.oxycblt.musikr.MusicParent import org.oxycblt.musikr.MusicParent
import org.oxycblt.musikr.fs.mediastore.MediaStore import org.oxycblt.musikr.fs.mediastore.MediaStore
import org.oxycblt.musikr.fs.saf.SAF import org.oxycblt.musikr.fs.saf.SAF
@@ -155,19 +156,7 @@ private constructor(
L.d("Music changed, updating shared objects") L.d("Music changed, updating shared objects")
// Wipe possibly-invalidated outdated covers // Wipe possibly-invalidated outdated covers
imageLoader.memoryCache?.clear() imageLoader.memoryCache?.clear()
// Clear invalid models from PlaybackStateManager. This is not connected reconcilePlaybackState(playbackManager, library, musicRepository)
// to a listener as it is bad practice for a shared object to attach to
// the listener system of another.
playbackManager.toSavedState()?.let { savedState ->
playbackManager.applySavedState(
savedState.copy(
parent =
savedState.parent?.let { musicRepository.find(it.uid) as? MusicParent? },
heap = savedState.heap.map { song -> song?.let { library.findSong(it.uid) } },
),
true,
)
}
} }
private fun startTracking() { private fun startTracking() {
@@ -232,5 +221,30 @@ private constructor(
companion object { companion object {
const val WAKELOCK_TIMEOUT_MS = 60 * 1000L const val WAKELOCK_TIMEOUT_MS = 60 * 1000L
/** Re-identify saved playback references against the latest published library. */
internal fun reconcilePlaybackState(
playbackManager: PlaybackStateManager,
library: Library,
musicRepository: MusicRepository,
) {
// This is not connected to a listener as it is bad practice for a shared object to
// attach to the listener system of another.
playbackManager.toSavedState()?.let { savedState ->
playbackManager.applySavedState(
savedState.copy(
parent =
savedState.parent?.let {
musicRepository.find(it.uid) as? MusicParent?
},
heap =
savedState.heap.map { song ->
song?.let { library.findSong(it.uid) }
},
),
true,
)
}
}
} }
} }
@@ -109,6 +109,8 @@ class PlaybackPanelFragment :
binding.playbackToolbar.apply { binding.playbackToolbar.apply {
setNavigationOnClickListener { playbackModel.openMain() } setNavigationOnClickListener { playbackModel.openMain() }
setOnMenuItemClickListener(this@PlaybackPanelFragment) setOnMenuItemClickListener(this@PlaybackPanelFragment)
// Tapping the Now Playing header navigates to the parent (album, playlist, etc.).
setOnClickListener { playbackModel.navigateToParent() }
} }
binding.playbackPager?.apply { binding.playbackPager?.apply {
@@ -119,7 +121,7 @@ class PlaybackPanelFragment :
UserAwarePagerCallback(this) { UserAwarePagerCallback(this) {
// Posting the queue goto command prevents the seekbar pos from desyncing // Posting the queue goto command prevents the seekbar pos from desyncing
// from the song's duration, which creates a visual flicker in the seekbar. // from the song's duration, which creates a visual flicker in the seekbar.
post { queueModel.goto(it) } post { queueModel.gotoTimelinePosition(it) }
} }
.also { it.attach() } .also { it.attach() }
setPageTransformer(CarouselTransformer()) setPageTransformer(CarouselTransformer())
@@ -275,8 +277,9 @@ class PlaybackPanelFragment :
private fun updateParent(parent: MusicParent?) { private fun updateParent(parent: MusicParent?) {
val binding = requireBinding() val binding = requireBinding()
val context = requireContext() val context = requireContext()
binding.playbackToolbar.subtitle = // No subtitle without a parent: the header carries a tap action, so it must not name
parent?.run { name.resolve(context) } ?: context.getString(R.string.lbl_all_songs) // a destination it cannot navigate to.
binding.playbackToolbar.subtitle = parent?.run { name.resolve(context) }
} }
private fun updatePosition(positionDs: Long) { private fun updatePosition(positionDs: Long) {
@@ -344,8 +347,9 @@ class PlaybackPanelFragment :
// but only on some devices. // but only on some devices.
val binding = binding ?: return val binding = binding ?: return
val command = playbackModel.pagerCommand.consume() val commands = playbackModel.drainPagerCommands()
if (command == null) { L.d("Pager: applying ${commands.size} command(s), pager at ${binding.playbackPager.currentItem}")
if (commands.isEmpty()) {
// This probably shouldn't happen in practice, as QueueViewModel directly // This probably shouldn't happen in practice, as QueueViewModel directly
// attaches to PlaybackStateManager and will basically always initialize // attaches to PlaybackStateManager and will basically always initialize
// with a command as a result. // with a command as a result.
@@ -357,9 +361,12 @@ class PlaybackPanelFragment :
return return
} }
// Apply every command in order; each carries the queue state it was made against, so a
// burst (like a drain's removal plus scroll) cannot lose its intermediate step.
for ((commandQueue, command) in commands) {
if (command.update != null) { if (command.update != null) {
// queue needs to be updated. // queue needs to be updated.
coverPagerAdapter.update(queue.queue, command.update) coverPagerAdapter.update(commandQueue.queue, command.update)
} }
if (command.scroll != null) { if (command.scroll != null) {
@@ -369,7 +376,7 @@ class PlaybackPanelFragment :
val delta = binding.playbackPager.currentItem - command.scroll val delta = binding.playbackPager.currentItem - command.scroll
if (delta == 0) { if (delta == 0) {
// user scroll, carry on // user scroll, carry on
return continue
} }
if (command.update == null && abs(delta) == 1) { if (command.update == null && abs(delta) == 1) {
binding.playbackPager.smoothScrollByPageTo(command.scroll) binding.playbackPager.smoothScrollByPageTo(command.scroll)
@@ -378,6 +385,7 @@ class PlaybackPanelFragment :
} }
} }
} }
}
private fun navigateToCurrentSong() { private fun navigateToCurrentSong() {
playbackModel.song.value?.let(detailModel::showAlbum) playbackModel.song.value?.let(detailModel::showAlbum)
@@ -101,13 +101,37 @@ constructor(
val openPanel: Event<OpenPanel> val openPanel: Event<OpenPanel>
field = MutableEvent<OpenPanel>() field = MutableEvent<OpenPanel>()
/** Requests navigation to the parent of the current playback, from the Now Playing header. */
val parentNavigation: Event<MusicParent>
field = MutableEvent<MusicParent>()
private val _pagerQueue = MutableStateFlow(PagerQueue(listOf(), 0)) private val _pagerQueue = MutableStateFlow(PagerQueue(listOf(), 0))
/** The current queue in a special bundled format suitable for the cover ViewPager2. */ /** The current queue in a special bundled format suitable for the cover ViewPager2. */
val pagerQueue: StateFlow<PagerQueue> = _pagerQueue val pagerQueue: StateFlow<PagerQueue> = _pagerQueue
/** Specialized ViewPager2-friendly queue commands */ // Manager callbacks can arrive on any thread; the panel drains on the main thread.
val pagerCommand: Event<PagerCommand> private val pagerLock = Any()
field = MutableEvent<PagerCommand>() private val pendingPagerCommands = ArrayDeque<Pair<PagerQueue, PagerCommand>>()
/**
* Drain the pager commands accumulated since the last drain, as (queue, command) pairs in
* order. Each pair is a complete intermediate state, so applying them sequentially is safe
* even when a single event (like a drain) produces several commands in one burst.
*/
fun drainPagerCommands(): List<Pair<PagerQueue, PagerCommand>> =
synchronized(pagerLock) {
val drained = pendingPagerCommands.toList()
pendingPagerCommands.clear()
drained
}
/** Update the pager's queue and enqueue the command describing the change. */
private fun updatePagerQueue(queue: List<Song>, index: Int, command: PagerCommand) {
val pagerQueue = PagerQueue(queue, index)
L.d("Pager: enqueue $command, queue size ${queue.size}, index $index")
synchronized(pagerLock) { pendingPagerCommands += pagerQueue to command }
_pagerQueue.value = pagerQueue
}
/** /**
* A [PlaybackDecision] command that is awaiting a view capable of responding to it. Null if * A [PlaybackDecision] command that is awaiting a view capable of responding to it. Null if
@@ -137,8 +161,7 @@ constructor(
positionDs.value = playbackManager.progression.calculateElapsedPositionMs().msToDs() positionDs.value = playbackManager.progression.calculateElapsedPositionMs().msToDs()
song.value = playbackManager.currentSong song.value = playbackManager.currentSong
pagerCommand.put(PagerCommand(update = null, scroll = index)) updatePagerQueue(_pagerQueue.value.queue, index, PagerCommand(update = null, scroll = index))
_pagerQueue.value = _pagerQueue.value.copy(index = index)
} }
override fun onQueueChanged(queue: List<Song>, index: Int, change: QueueChange) { override fun onQueueChanged(queue: List<Song>, index: Int, change: QueueChange) {
@@ -148,21 +171,21 @@ constructor(
song.value = playbackManager.currentSong song.value = playbackManager.currentSong
} }
pagerCommand.put( updatePagerQueue(
queue,
index,
PagerCommand( PagerCommand(
update = change.instructions, update = change.instructions,
scroll = index.takeIf { change.type != QueueChange.Type.MAPPING }, scroll = index.takeIf { change.type != QueueChange.Type.MAPPING },
),
) )
)
_pagerQueue.value = PagerQueue(queue = queue, index = index)
} }
override fun onQueueReordered(queue: List<Song>, index: Int, isShuffled: Boolean) { override fun onQueueReordered(queue: List<Song>, index: Int, isShuffled: Boolean) {
L.d("Queue completely changed, updating current song") L.d("Queue completely changed, updating current song")
this.isShuffled.value = isShuffled this.isShuffled.value = isShuffled
pagerCommand.put(PagerCommand(update = UpdateInstructions.Replace(0), scroll = index)) updatePagerQueue(queue, index, PagerCommand(update = UpdateInstructions.Replace(0), scroll = index))
_pagerQueue.value = PagerQueue(queue = queue, index = index)
} }
override fun onNewPlayback( override fun onNewPlayback(
@@ -176,8 +199,7 @@ constructor(
_parent.value = parent _parent.value = parent
this.isShuffled.value = isShuffled this.isShuffled.value = isShuffled
pagerCommand.put(PagerCommand(update = UpdateInstructions.Replace(0), scroll = index)) updatePagerQueue(queue, index, PagerCommand(update = UpdateInstructions.Replace(0), scroll = index))
_pagerQueue.value = PagerQueue(queue = queue, index = index)
} }
override fun onProgressionChanged(progression: Progression) { override fun onProgressionChanged(progression: Progression) {
@@ -632,6 +654,12 @@ constructor(
/** Open the main panel, closing all other panels. */ /** Open the main panel, closing all other panels. */
fun openMain() = openImpl(OpenPanel.MAIN) fun openMain() = openImpl(OpenPanel.MAIN)
/** Navigate to the parent of the current playback. Does nothing when playback is parentless. */
fun navigateToParent() {
val parent = parent.value ?: return
parentNavigation.put(parent)
}
/** Open the playback panel, closing the queue panel if needed. */ /** Open the playback panel, closing the queue panel if needed. */
fun openPlayback() = openImpl(OpenPanel.PLAYBACK) fun openPlayback() = openImpl(OpenPanel.PLAYBACK)
@@ -0,0 +1,82 @@
/*
* Copyright (c) 2026 Auxio Project
* DeckRowDiff.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.queue
import org.oxycblt.auxio.list.adapter.UpdateInstructions
import org.oxycblt.musikr.Song
/**
* Compute the minimal [UpdateInstructions] transforming the queue drawer's rows from [old] to
* [new]. Returns null when nothing changed. Falls back to [UpdateInstructions.Replace] from the
* first divergence when no single add, remove, or move explains the change.
*/
internal fun diffDeckRows(old: List<Song>, new: List<Song>): UpdateInstructions? {
val oldUids = old.map { it.uid }
val newUids = new.map { it.uid }
if (oldUids == newUids) {
return null
}
// Common prefix and suffix frame the changed window.
var prefix = 0
while (prefix < minOf(oldUids.size, newUids.size) && oldUids[prefix] == newUids[prefix]) {
prefix++
}
var suffix = 0
while (suffix < minOf(oldUids.size, newUids.size) - prefix &&
oldUids[oldUids.size - 1 - suffix] == newUids[newUids.size - 1 - suffix]
) {
suffix++
}
val oldWindow = oldUids.subList(prefix, oldUids.size - suffix)
val newWindow = newUids.subList(prefix, newUids.size - suffix)
return when {
// Pure addition or removal.
oldWindow.isEmpty() -> UpdateInstructions.Add(prefix, newWindow.size)
newWindow.isEmpty() -> UpdateInstructions.Remove(prefix, oldWindow.size)
// A single element moved within the window.
oldWindow.size == newWindow.size -> {
val move = findSingleMove(oldWindow, newWindow)
if (move != null) {
UpdateInstructions.Move(prefix + move.first, prefix + move.second)
} else {
UpdateInstructions.Replace(prefix)
}
}
else -> UpdateInstructions.Replace(prefix)
}
}
/**
* Find the single element move transforming [old] into [new], as its indices in each list. Null
* when no single move explains the difference (including replacements, which equalize on removal
* without the element actually moving).
*/
private fun <T> findSingleMove(old: List<T>, new: List<T>): Pair<Int, Int>? {
for (from in old.indices) {
val remainder = old.toMutableList().apply { removeAt(from) }
for (to in new.indices) {
if (old[from] == new[to] && new.toMutableList().apply { removeAt(to) } == remainder) {
return from to to
}
}
}
return null
}
@@ -51,7 +51,7 @@ class QueueAdapter(private val listener: EditClickListListener<Song>) :
// Since PlayingIndicator adapter relies on an item value, we cannot use it for this // Since PlayingIndicator adapter relies on an item value, we cannot use it for this
// adapter, as one item can appear at several points in the UI. Use a similar implementation // adapter, as one item can appear at several points in the UI. Use a similar implementation
// with an index value instead. // with an index value instead.
private var currentIndex = 0 private var currentIndex = -1
private var isPlaying = false private var isPlaying = false
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
@@ -69,7 +69,6 @@ class QueueAdapter(private val listener: EditClickListListener<Song>) :
viewHolder.bind(getItem(position), listener) viewHolder.bind(getItem(position), listener)
} }
viewHolder.isFuture = position > currentIndex
viewHolder.updatePlayingIndicator(position == currentIndex, isPlaying) viewHolder.updatePlayingIndicator(position == currentIndex, isPlaying)
} }
@@ -91,7 +90,7 @@ class QueueAdapter(private val listener: EditClickListListener<Song>) :
// TODO: Don't update when the index has not moved. // TODO: Don't update when the index has not moved.
if (currentIndex < lastIndex) { if (currentIndex < lastIndex) {
L.d("Moved backwards, must update items above last index") L.d("Moved backwards, must update items above last index")
val since = if (incremental) currentIndex else 0 val since = (if (incremental) currentIndex else 0).coerceAtLeast(0)
notifyItemRangeChanged( notifyItemRangeChanged(
since, since,
lastIndex - since + 1, lastIndex - since + 1,
@@ -99,17 +98,20 @@ class QueueAdapter(private val listener: EditClickListListener<Song>) :
) )
} else if (currentIndex > lastIndex) { } else if (currentIndex > lastIndex) {
L.d("Moved forwards, update items after index") L.d("Moved forwards, update items after index")
val since = if (incremental) lastIndex else 0 val since = (if (incremental) lastIndex else 0).coerceAtLeast(0)
notifyItemRangeChanged( notifyItemRangeChanged(
since, since,
currentIndex - since + 1, currentIndex - since + 1,
PAYLOAD_UPDATE_POSITION, PAYLOAD_UPDATE_POSITION,
) )
} else if (!incremental && currentIndex >= 0) {
// A list operation replaced the playing row's occupant without moving the index.
notifyItemChanged(currentIndex, PAYLOAD_UPDATE_POSITION)
} }
val lastIsPlaying = this.isPlaying val lastIsPlaying = this.isPlaying
this.isPlaying = isPlaying this.isPlaying = isPlaying
if (this.isPlaying != lastIsPlaying) { if (currentIndex >= 0 && this.isPlaying != lastIsPlaying) {
L.d("Changed play state") L.d("Changed play state")
notifyItemChanged(currentIndex) notifyItemChanged(currentIndex)
} }
@@ -128,7 +130,11 @@ class QueueAdapter(private val listener: EditClickListListener<Song>) :
*/ */
class QueueSongViewHolder private constructor(private val binding: ItemEditableSongBinding) : class QueueSongViewHolder private constructor(private val binding: ItemEditableSongBinding) :
PlayingIndicatorAdapter.ViewHolder(binding.root), MaterialDragCallback.ViewHolder { PlayingIndicatorAdapter.ViewHolder(binding.root), MaterialDragCallback.ViewHolder {
override val enabled = true /** Whether this row is the playing row; the playing row is neither draggable nor swipeable. */
private var isActiveRow = false
override val enabled: Boolean
get() = !isActiveRow
override val root = binding.root override val root = binding.root
override val body = binding.body override val body = binding.body
override val delete = binding.background override val delete = binding.background
@@ -143,18 +149,6 @@ class QueueSongViewHolder private constructor(private val binding: ItemEditableS
fillColor = binding.context.getAttrColorCompat(MR.attr.colorSurfaceContainerHigh) fillColor = binding.context.getAttrColorCompat(MR.attr.colorSurfaceContainerHigh)
} }
/**
* Whether this ViewHolder should be full-opacity to represent a future item, or greyed out to
* represent a past item. True if former, false if latter.
*/
var isFuture: Boolean
get() = binding.songAlbumCover.isEnabled
set(value) {
binding.songAlbumCover.isEnabled = value
binding.songName.isEnabled = value
binding.songInfo.isEnabled = value
}
init { init {
binding.body.background = LayerDrawable(arrayOf(roundableBackground, liftableBackground)) binding.body.background = LayerDrawable(arrayOf(roundableBackground, liftableBackground))
} }
@@ -177,8 +171,11 @@ class QueueSongViewHolder private constructor(private val binding: ItemEditableS
} }
override fun updatePlayingIndicator(isActive: Boolean, isPlaying: Boolean) { override fun updatePlayingIndicator(isActive: Boolean, isPlaying: Boolean) {
isActiveRow = isActive
binding.interactBody.isSelected = isActive binding.interactBody.isSelected = isActive
binding.songAlbumCover.setPlaying(isPlaying) binding.songAlbumCover.setPlaying(isPlaying)
// The playing row is neither draggable nor swipeable; hide the drag affordance.
binding.songDragHandle.isInvisible = isActive
} }
companion object { companion object {
@@ -23,6 +23,7 @@ import android.util.AttributeSet
import android.view.View import android.view.View
import android.view.WindowInsets import android.view.WindowInsets
import androidx.coordinatorlayout.widget.CoordinatorLayout import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.view.updatePadding
import com.google.android.material.R as MR import com.google.android.material.R as MR
import com.google.android.material.shape.MaterialShapeDrawable import com.google.android.material.shape.MaterialShapeDrawable
import com.google.android.material.shape.ShapeAppearanceModel import com.google.android.material.shape.ShapeAppearanceModel
@@ -106,6 +107,10 @@ class QueueBottomSheetBehavior<V : View>(context: Context, attributeSet: Attribu
val bars = insets.systemBarInsetsCompat val bars = insets.systemBarInsetsCompat
val effectiveBarHeight = if (barHeight > 0) barHeight else getIdealBarHeight(child.context) val effectiveBarHeight = if (barHeight > 0) barHeight else getIdealBarHeight(child.context)
expandedOffset = effectiveBarHeight + barSpacing expandedOffset = effectiveBarHeight + barSpacing
// The sheet is measured at full height from its expanded offset, so its bottom extends
// that far below the screen. Pad the content so it ends at the visible bottom instead
// (which also keeps the empty-queue hint visually centered).
child.updatePadding(bottom = expandedOffset + bars.bottom)
return insets.replaceSystemBarInsetsCompat( return insets.replaceSystemBarInsetsCompat(
bars.left, bars.left,
bars.top, bars.top,
@@ -21,6 +21,7 @@ package org.oxycblt.auxio.playback.queue
import android.os.Bundle import android.os.Bundle
import android.view.LayoutInflater import android.view.LayoutInflater
import androidx.core.view.isInvisible import androidx.core.view.isInvisible
import androidx.core.view.isVisible
import androidx.fragment.app.activityViewModels import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.ItemTouchHelper
@@ -88,9 +89,9 @@ class QueueFragment : ViewBindingFragment<FragmentQueueBinding>(), EditClickList
super.onDestroyBinding(binding) super.onDestroyBinding(binding)
touchHelper = null touchHelper = null
binding.queueRecycler.adapter = null binding.queueRecycler.adapter = null
// Avoid possible race conditions that could cause a bad instruction to be consumed // Discard any updates accumulated while the view was gone; a recreated view rebuilds
// during list initialization and crash the app. Could happen if the user is fast enough. // from the current rows.
queueModel.queueInstructions.consume() queueModel.drainQueueUpdates()
} }
override fun onClick(item: Song, viewHolder: RecyclerView.ViewHolder) { override fun onClick(item: Song, viewHolder: RecyclerView.ViewHolder) {
@@ -111,9 +112,10 @@ class QueueFragment : ViewBindingFragment<FragmentQueueBinding>(), EditClickList
private fun updateQueue(queue: List<Song>, index: Int, isPlaying: Boolean) { private fun updateQueue(queue: List<Song>, index: Int, isPlaying: Boolean) {
val binding = requireBinding() val binding = requireBinding()
val instructions = queueModel.queueInstructions.consume() val updates = queueModel.drainQueueUpdates()
queueAdapter.update(queue, instructions) updates.forEach { (rows, instructions) -> queueAdapter.update(rows, instructions) }
queueAdapter.setPosition(index, isPlaying, instructions == null) queueAdapter.setPosition(index, isPlaying, updates.isEmpty())
binding.queueEmpty.isVisible = queue.isEmpty()
// If requested, scroll to a new item (occurs when the index moves) // If requested, scroll to a new item (occurs when the index moves)
val scrollTo = queueModel.scrollTo.consume() val scrollTo = queueModel.scrollTo.consume()
@@ -33,7 +33,8 @@ import org.oxycblt.musikr.Song
import timber.log.Timber as L import timber.log.Timber as L
/** /**
* A [ViewModel] that manages the current queue state and allows navigation through the queue. * A [ViewModel] that exposes the deck as the queue drawer's rows and translates drawer-row
* actions into deck coordinates.
* *
* @author Alexander Capehart (OxygenCobalt) * @author Alexander Capehart (OxygenCobalt)
*/ */
@@ -42,49 +43,53 @@ class QueueViewModel @Inject constructor(private val playbackManager: PlaybackSt
ViewModel(), PlaybackStateManager.Listener { ViewModel(), PlaybackStateManager.Listener {
private val _queue = MutableStateFlow(listOf<Song>()) private val _queue = MutableStateFlow(listOf<Song>())
/** The current queue. */ /** The drawer rows: the playing deck song (if any) followed by the waiting deck songs. */
val queue: StateFlow<List<Song>> = _queue val queue: StateFlow<List<Song>> = _queue
private val _queueInstructions = MutableEvent<UpdateInstructions>()
/** Instructions for how to update [queue] in the UI. */ // Manager callbacks can arrive on any thread; the fragment drains on the main thread.
val queueInstructions: Event<UpdateInstructions> = _queueInstructions private val pendingLock = Any()
private val pendingUpdates = ArrayDeque<Pair<List<Song>, UpdateInstructions>>()
/**
* Drain the row updates accumulated since the last drain, as (rows, instructions) pairs in
* order. Each pair is a complete intermediate state, so applying them sequentially is safe
* even when flow emissions were conflated.
*/
fun drainQueueUpdates(): List<Pair<List<Song>, UpdateInstructions>> =
synchronized(pendingLock) {
val drained = pendingUpdates.toList()
pendingUpdates.clear()
drained
}
/** Controls whether the queue should be force-scrolled to a particular location. */ /** Controls whether the queue should be force-scrolled to a particular location. */
val scrollTo: Event<Int> val scrollTo: Event<Int>
field = MutableEvent<Int>() field = MutableEvent<Int>()
/** The index of the currently playing song in the queue. */ /** The row of the playing deck song (0), or -1 when no deck song is playing. */
val index: StateFlow<Int> val index: StateFlow<Int>
field = MutableStateFlow(playbackManager.index) field = MutableStateFlow(-1)
init { init {
playbackManager.addListener(this) playbackManager.addListener(this)
republish()
} }
override fun onIndexMoved(index: Int) { override fun onIndexMoved(index: Int) {
L.d("Index moved, synchronizing and scrolling to new position") val hadPlayingDeckSong = this.index.value == 0
scrollTo.put(index) republish()
this.index.value = index if (!hadPlayingDeckSong && this.index.value == 0) {
// A deck song started playing; make sure it is visible.
scrollTo.put(0)
}
} }
override fun onQueueChanged(queue: List<Song>, index: Int, change: QueueChange) { override fun onQueueChanged(queue: List<Song>, index: Int, change: QueueChange) {
// Queue changed trivially due to item mo -> Diff queue, stay at current index. republish()
L.d("Updating queue display")
_queueInstructions.put(change.instructions)
_queue.value = queue
if (change.type != QueueChange.Type.MAPPING) {
// Index changed, make sure it remains updated without actually scrolling to it.
L.d("Index changed with queue, synchronizing new position")
this.index.value = index
}
} }
override fun onQueueReordered(queue: List<Song>, index: Int, isShuffled: Boolean) { override fun onQueueReordered(queue: List<Song>, index: Int, isShuffled: Boolean) {
// Queue changed completely -> Replace queue, update index republish()
L.d("Queue changed completely, replacing queue and position")
_queueInstructions.put(UpdateInstructions.Replace(0))
scrollTo.put(index)
_queue.value = queue
this.index.value = index
} }
override fun onNewPlayback( override fun onNewPlayback(
@@ -93,12 +98,7 @@ class QueueViewModel @Inject constructor(private val playbackManager: PlaybackSt
index: Int, index: Int,
isShuffled: Boolean, isShuffled: Boolean,
) { ) {
// Entirely new queue -> Replace queue, update index republish()
L.d("New playback, replacing queue and position")
_queueInstructions.put(UpdateInstructions.Replace(0))
scrollTo.put(index)
_queue.value = queue
this.index.value = index
} }
override fun onCleared() { override fun onCleared() {
@@ -106,46 +106,82 @@ class QueueViewModel @Inject constructor(private val playbackManager: PlaybackSt
} }
/** /**
* Start playing the the queue item at the given index. * Start playing the deck row at the given index.
* *
* @param adapterIndex The index of the queue item to play. Does nothing if the index is out of * @param adapterIndex The deck row to play. Does nothing if the row is out of range.
* range.
*/ */
fun goto(adapterIndex: Int) { fun goto(adapterIndex: Int) {
if (adapterIndex !in queue.value.indices) { if (adapterIndex !in queue.value.indices) {
return return
} }
L.d("Going to position $adapterIndex in queue") L.d("Going to deck row $adapterIndex")
playbackManager.goto(adapterIndex) playbackManager.gotoDeck(adapterIndex)
} }
/** /**
* Remove a queue item at the given index. * Jump to the timeline position at the given index, as the cover pager does. The pager
* mirrors the whole timeline, so this speaks timeline coordinates rather than deck rows.
* *
* @param adapterIndex The index of the queue item to play. Does nothing if the index is out of * @param timelineIndex The timeline position to play. Does nothing if out of range.
* range. */
fun gotoTimelinePosition(timelineIndex: Int) {
if (timelineIndex !in playbackManager.queue.indices) {
return
}
L.d("Going to timeline position $timelineIndex")
playbackManager.goto(timelineIndex)
}
/**
* Remove the deck row at the given index.
*
* @param adapterIndex The deck row to remove. Does nothing if the row is out of range.
*/ */
fun removeQueueDataItem(adapterIndex: Int) { fun removeQueueDataItem(adapterIndex: Int) {
if (adapterIndex !in queue.value.indices) { if (adapterIndex !in queue.value.indices) {
return return
} }
L.d("Removing item $adapterIndex in queue") L.d("Removing deck row $adapterIndex")
playbackManager.removeQueueItem(adapterIndex) playbackManager.removeDeckItem(adapterIndex)
} }
/** /**
* Move a queue item from one index to another index. * Move a deck row from one index to another.
* *
* @param adapterFrom The index of the queue item to move. * @param adapterFrom The deck row to move.
* @param adapterTo The destination index for the queue item. * @param adapterTo The destination deck row.
* @return true if the items were moved, false otherwise. * @return true if the rows were moved, false otherwise.
*/ */
fun moveQueueDataItems(adapterFrom: Int, adapterTo: Int): Boolean { fun moveQueueDataItems(adapterFrom: Int, adapterTo: Int): Boolean {
if (adapterFrom !in queue.value.indices || adapterTo !in queue.value.indices) { if (adapterFrom !in queue.value.indices || adapterTo !in queue.value.indices) {
return false return false
} }
L.d("Moving $adapterFrom to $adapterFrom in queue") L.d("Moving deck row $adapterFrom to row $adapterTo")
playbackManager.moveQueueItem(adapterFrom, adapterTo) playbackManager.moveDeckItems(adapterFrom, adapterTo)
return true return true
} }
/** Clear the queue of all waiting deck songs. */
fun clearQueue() {
L.d("Clearing the queue")
playbackManager.clearQueue()
}
/** Randomly reorder the waiting deck songs; the playing row keeps its place. */
fun shuffleDeck() {
L.d("Shuffling the deck")
playbackManager.shuffleDeck()
}
/** Republish the drawer rows from the manager's deck state. */
private fun republish() {
val rows = listOfNotNull(playbackManager.deckCurrent) + playbackManager.deck
val instructions = diffDeckRows(_queue.value, rows)
if (instructions != null) {
// Complete (rows, instruction) pairs chain correctly under flow conflation.
synchronized(pendingLock) { pendingUpdates += rows to instructions }
}
_queue.value = rows
index.value = if (playbackManager.deckCurrent != null) 0 else -1
}
} }
@@ -287,6 +287,53 @@ class ExoPlaybackStateHolder(
deferSave() deferSave()
} }
override fun shuffleDeck(deckSize: Int, ack: StateAck.ShuffleDeck) {
if (player.currentTimeline.isEmpty || deckSize < 2) {
return
}
val current = player.currentMediaItemIndex
// Walk the play order before touching the timeline: the waiting deck block occupies
// the positions directly behind the current song, and the rest keeps its sequence.
val playOrder = player.unscrambleQueueIndices()
check(playOrder.size >= 1 + deckSize) { "Deck block missing from the timeline" }
val anchor = playOrder[0]
// Extract the block, permute it, and put it back: the physical order is the deck's
// order.
val block =
(current + 1 until current + 1 + deckSize).map {
checkNotNull(player.getMediaItemAt(it).song) { "Untagged media item in the deck block" }
}
player.removeMediaItems(current + 1, current + 1 + deckSize)
player.addMediaItems(current + 1, block.shuffled().map { it.buildMediaItem() })
if (player.shuffleModeEnabled) {
// Re-pin the new deck order after the current song; the rest of the play order
// keeps its sequence. A disturbed order (moves under shuffle leave the shuffle
// order stale) can walk short or with duplicates, so the splice is validated and
// otherwise falls back to repinning the whole order.
val timelineSize = player.mediaItemCount
val rest =
playOrder
.filterNot { it == anchor || it in current + 1..current + deckSize }
.distinct()
val order =
listOf(anchor) + (current + 1 until current + 1 + deckSize).toList() + rest
val valid =
order.size == timelineSize &&
order.all { it in 0 until timelineSize } &&
order.toSet().size == timelineSize
if (valid) {
player.setShuffleOrder(BetterShuffleOrder(order.toIntArray()))
} else {
L.w("Deck shuffle order splice invalid; repinning the whole order")
player.setShuffleOrder(
BetterShuffleOrder.createDeckPinned(timelineSize, anchor, deckSize)
)
}
}
playbackManager.ack(this, ack)
deferSave()
}
override fun next() { override fun next() {
// Replicate the old pseudo-circular queue behavior when no repeat option is implemented. // Replicate the old pseudo-circular queue behavior when no repeat option is implemented.
// Basically, you can't skip back and wrap around the queue, but you can skip forward and // Basically, you can't skip back and wrap around the queue, but you can skip forward and
@@ -145,6 +145,15 @@ interface PlaybackStateHolder {
*/ */
fun shuffled(shuffled: Boolean, deckSize: Int) fun shuffled(shuffled: Boolean, deckSize: Int)
/**
* Randomly reorder the waiting deck songs, which physically occupy the positions directly
* behind the current song.
*
* @param deckSize The number of waiting deck songs to permute.
* @param ack The [StateAck] to return to [PlaybackStateManager].
*/
fun shuffleDeck(deckSize: Int, ack: StateAck.ShuffleDeck)
/** /**
* Handle a deferred playback action. * Handle a deferred playback action.
* *
@@ -206,6 +215,9 @@ sealed interface StateAck {
/** @see PlaybackStateHolder.shuffled */ /** @see PlaybackStateHolder.shuffled */
data object QueueReordered : StateAck data object QueueReordered : StateAck
/** @see PlaybackStateHolder.shuffleDeck */
data object ShuffleDeck : StateAck
/** /**
* @see PlaybackStateHolder.newPlayback * @see PlaybackStateHolder.newPlayback
* @see PlaybackStateHolder.applySavedState * @see PlaybackStateHolder.applySavedState
@@ -60,6 +60,12 @@ interface PlaybackStateManager {
/** The current queue of [Song]s. */ /** The current queue of [Song]s. */
val queue: List<Song> val queue: List<Song>
/** The upcoming deck [Song]s, in order. The deck sits directly behind the current song. */
val deck: List<Song>
/** The current [Song] when it came from the deck. Null when the heap is playing. */
val deckCurrent: Song?
/** The index of the currently playing [Song] in the queue. */ /** The index of the currently playing [Song] in the queue. */
val index: Int val index: Int
@@ -192,6 +198,47 @@ interface PlaybackStateManager {
*/ */
fun removeQueueItem(at: Int) fun removeQueueItem(at: Int)
/**
* Clear the queue of all waiting deck [Song]s. The currently playing [Song] is unaffected,
* even if it came from the deck.
*/
fun clearQueue()
/**
* Randomly reorder the waiting deck [Song]s. The currently playing [Song] is unaffected,
* even if it came from the deck, and the heap keeps its order.
*/
fun shuffleDeck()
/**
* Start playing the deck [Song] at the given drawer row. Row 0 is the currently playing
* deck [Song] when there is one (tapping it restarts the song); otherwise the rows are the
* waiting deck [Song]s in order. A tapped waiting [Song] plays immediately while the rest
* of the deck keeps its place and order: a displaced playing deck [Song] drains, a
* displaced heap [Song] passes by as if played.
*
* @param row The drawer row to play. Does nothing if out of range.
*/
fun gotoDeck(row: Int)
/**
* Remove the deck [Song] at the given drawer row. Only waiting rows are removable; the
* playing row is refused.
*
* @param row The drawer row to remove. Does nothing if it is the playing row or out of
* range.
*/
fun removeDeckItem(row: Int)
/**
* Move the deck [Song] at one drawer row to another. Only waiting rows participate; drags
* involving the playing row are refused.
*
* @param fromRow The drawer row of the [Song] to move.
* @param toRow The drawer row to move it to.
*/
fun moveDeckItems(fromRow: Int, toRow: Int)
/** /**
* (Re)shuffle or (Re)order this instance. * (Re)shuffle or (Re)order this instance.
* *
@@ -382,10 +429,12 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
@Volatile private var isInitialized = false @Volatile private var isInitialized = false
/** The upcoming deck songs, in order. The deck sits directly behind the current song. */ /** The upcoming deck songs, in order. The deck sits directly behind the current song. */
private var deck = emptyList<Song>() override var deck = emptyList<Song>()
private set
/** The current song when it came from the deck. Null when the heap is playing. */ /** The current song when it came from the deck. Null when the heap is playing. */
private var deckCurrent: Song? = null override var deckCurrent: Song? = null
private set
override val progression override val progression
get() = stateMirror.progression get() = stateMirror.progression
@@ -513,9 +562,8 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
} else { } else {
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")
// The ack joins the songs to the deck, so that listeners observe the final state.
stateHolder.playNext(songs, StateAck.PlayNext(stateMirror.index + 1, songs.size)) stateHolder.playNext(songs, StateAck.PlayNext(stateMirror.index + 1, songs.size))
// Play-next joins the front of the deck.
deck = songs + deck
} }
} }
@@ -540,8 +588,8 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
val stateHolder = stateHolder ?: return val stateHolder = stateHolder ?: return
val at = stateMirror.index + 1 + deck.size 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")
// The ack grows the deck, so that listeners observe the final state.
stateHolder.playAfter(songs, StateAck.PlayNext(at, songs.size)) stateHolder.playAfter(songs, StateAck.PlayNext(at, songs.size))
deck = deck + songs
} }
} }
@@ -565,6 +613,81 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
stateHolder.remove(at, StateAck.Remove(at)) stateHolder.remove(at, StateAck.Remove(at))
} }
@Synchronized
override fun clearQueue() {
val stateHolder = stateHolder ?: return
L.d("Clearing the deck (${deck.size} waiting songs)")
// The waiting deck entries sit directly behind the current song; removing at the same
// position repeatedly pops them in order. The ack handler shrinks the deck each time.
while (deck.isNotEmpty()) {
stateHolder.remove(stateMirror.index + 1, StateAck.Remove(stateMirror.index + 1))
}
}
@Synchronized
override fun shuffleDeck() {
val stateHolder = stateHolder ?: return
if (deck.size < 2) {
L.d("Too few waiting deck entries to shuffle")
return
}
L.d("Shuffling the deck (${deck.size} waiting songs)")
stateHolder.shuffleDeck(deck.size, StateAck.ShuffleDeck)
}
@Synchronized
override fun gotoDeck(row: Int) {
val stateHolder = stateHolder ?: return
val rowCount = deck.size + if (deckCurrent != null) 1 else 0
if (row !in 0 until rowCount) {
return
}
L.d("Going to deck row $row")
if (deckCurrent != null && row == 0) {
// Tapping the playing row restarts the song.
stateHolder.goto(stateMirror.index)
return
}
// Pull the target to the front of the deck block and step into it. The move ack keeps
// the rest of the deck in order behind it; the goto ack drains a displaced playing deck
// song and marks the target as the playing deck song.
val deckIndex = if (deckCurrent != null) row - 1 else row
val targetAt = stateMirror.index + 1 + deckIndex
val frontAt = stateMirror.index + 1
if (deckIndex > 0) {
stateHolder.move(targetAt, frontAt, StateAck.Move(targetAt, frontAt))
}
stateHolder.goto(frontAt)
}
@Synchronized
override fun removeDeckItem(row: Int) {
val stateHolder = stateHolder ?: return
// Only waiting entries are removable; the playing row plays on.
val deckIndex = if (deckCurrent != null) row - 1 else row
if (deckIndex !in deck.indices) {
return
}
L.d("Removing deck row $row")
val at = stateMirror.index + 1 + deckIndex
stateHolder.remove(at, StateAck.Remove(at))
}
@Synchronized
override fun moveDeckItems(fromRow: Int, toRow: Int) {
val stateHolder = stateHolder ?: return
// Only waiting entries are draggable; the playing row stays put.
val fromIndex = if (deckCurrent != null) fromRow - 1 else fromRow
val toIndex = if (deckCurrent != null) toRow - 1 else toRow
if (fromIndex !in deck.indices || toIndex !in deck.indices) {
return
}
L.d("Moving deck row $fromRow to row $toRow")
val from = stateMirror.index + 1 + fromIndex
val to = stateMirror.index + 1 + toIndex
stateHolder.move(from, to, StateAck.Move(from, to))
}
@Synchronized @Synchronized
override fun shuffled(shuffled: Boolean) { override fun shuffled(shuffled: Boolean) {
val stateHolder = stateHolder ?: return val stateHolder = stateHolder ?: return
@@ -638,7 +761,6 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
val departedAt = stateMirror.index 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)
listeners.forEach { it.onIndexMoved(stateMirror.index) }
// Leaving a deck song drains it: a different song is playing now. A rewind // Leaving a deck song drains it: a different song is playing now. A rewind
// acks without departing and drains nothing. // acks without departing and drains nothing.
if (departed != null && departed !== currentSong && departed === deckCurrent) { if (departed != null && departed !== currentSong && departed === deckCurrent) {
@@ -650,12 +772,21 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
deckCurrent = deck[0] deckCurrent = deck[0]
deck = deck.drop(1) deck = deck.drop(1)
} }
// Notify only after the deck bookkeeping settles, so listeners observe the
// final state.
listeners.forEach { it.onIndexMoved(stateMirror.index) }
} }
is StateAck.PlayNext -> { is StateAck.PlayNext -> {
val rawQueue = stateHolder.resolveQueue() val rawQueue = stateHolder.resolveQueue()
val change = val change =
QueueChange(QueueChange.Type.MAPPING, UpdateInstructions.Add(ack.at, ack.size)) QueueChange(QueueChange.Type.MAPPING, UpdateInstructions.Add(ack.at, ack.size))
stateMirror = stateMirror.copy(queue = rawQueue.resolveSongs(), rawQueue = rawQueue) stateMirror = stateMirror.copy(queue = rawQueue.resolveSongs(), rawQueue = rawQueue)
// The inserted songs join the deck before anyone is told, so listeners observe
// the final state. The insert lands at the deck's end (playAfter) or front
// (playNext).
val block = stateMirror.queue.subList(ack.at, ack.at + ack.size)
val deckInsertAt = (ack.at - (stateMirror.index + 1)).coerceIn(0, deck.size)
deck = deck.toMutableList().apply { addAll(deckInsertAt, block) }
listeners.forEach { listeners.forEach {
it.onQueueChanged(stateMirror.queue, stateMirror.index, change) it.onQueueChanged(stateMirror.queue, stateMirror.index, change)
} }
@@ -760,6 +891,34 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
) )
} }
} }
is StateAck.ShuffleDeck -> {
val rawQueue = stateHolder.resolveQueue()
stateMirror = stateMirror.copy(queue = rawQueue.resolveSongs(), rawQueue = rawQueue)
// The waiting deck is exactly the block behind the current song, and the
// shuffle only permutes it: re-extract it from the authoritative queue,
// guarding that the operation moved nothing else.
val block =
stateMirror.queue.subList(
stateMirror.index + 1,
stateMirror.index + 1 + deck.size,
)
val before = deck.map { it.uid }.toSet()
val after = block.map { it.uid }.toSet()
if (before != after) {
L.w("Deck shuffle changed deck membership; reconciling from the queue")
}
deck = block.toList()
listeners.forEach {
it.onQueueChanged(
stateMirror.queue,
stateMirror.index,
QueueChange(
QueueChange.Type.MAPPING,
UpdateInstructions.Replace(stateMirror.index + 1),
),
)
}
}
is StateAck.NewPlayback -> { is StateAck.NewPlayback -> {
val rawQueue = stateHolder.resolveQueue() val rawQueue = stateHolder.resolveQueue()
stateMirror = stateMirror =
@@ -917,5 +1076,16 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
deckCurrent = if (savedState.deckCurrent) currentSong else null deckCurrent = if (savedState.deckCurrent) currentSong else null
isInitialized = true isInitialized = true
// The deck restore ran after the holder's NewPlayback ack; re-notify with the final
// state so listeners observe the restored deck.
listeners.forEach {
it.onNewPlayback(
savedState.parent,
stateMirror.queue,
stateMirror.index,
stateMirror.rawQueue.isShuffled,
)
}
} }
} }
@@ -31,10 +31,12 @@ import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.ItemTouchHelper
import com.google.android.material.transition.MaterialSharedAxis import com.google.android.material.transition.MaterialSharedAxis
import dagger.hilt.android.AndroidEntryPoint import dagger.hilt.android.AndroidEntryPoint
import org.oxycblt.auxio.R import org.oxycblt.auxio.R
import org.oxycblt.auxio.databinding.FragmentSearchBinding import org.oxycblt.auxio.databinding.FragmentSearchBinding
import org.oxycblt.auxio.list.recycler.SwipeActionsCallback
import org.oxycblt.auxio.detail.DetailViewModel import org.oxycblt.auxio.detail.DetailViewModel
import org.oxycblt.auxio.detail.Show import org.oxycblt.auxio.detail.Show
import org.oxycblt.auxio.list.Item import org.oxycblt.auxio.list.Item
@@ -181,6 +183,18 @@ class SearchFragment : ListFragment<Music, FragmentSearchBinding>() {
} }
} }
ItemTouchHelper(
SwipeActionsCallback(isEnabled = { listModel.selected.value.isEmpty() }) {
song,
action ->
when (action) {
SwipeActionsCallback.SwipeAction.QUEUE -> playbackModel.addToQueue(song)
SwipeActionsCallback.SwipeAction.PLAY_NEXT -> playbackModel.playNext(song)
}
}
)
.attachToRecyclerView(binding.searchRecycler)
// --- VIEWMODEL SETUP --- // --- VIEWMODEL SETUP ---
collectImmediately(searchModel.searchResults, ::updateSearchResults) collectImmediately(searchModel.searchResults, ::updateSearchResults)
@@ -1,11 +1,15 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<!-- Lucide 'list-start' (lucide-static v1.72.0, ISC License) -->
<vector xmlns:android="http://schemas.android.com/apk/res/android" <vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp" android:width="24dp"
android:height="24dp" android:height="24dp"
android:tint="?attr/colorControlNormal" android:tint="?attr/colorControlNormal"
android:viewportWidth="960" android:viewportWidth="24"
android:viewportHeight="960"> android:viewportHeight="24">
<path <path
android:fillColor="@android:color/white" android:strokeColor="@android:color/white"
android:pathData="M780,900L720,840L840,720L720,600L780,540L960,720L780,900ZM320,840L320,760L160,760Q127,760 103.5,736.5Q80,713 80,680L80,200Q80,167 103.5,143.5Q127,120 160,120L800,120Q833,120 856.5,143.5Q880,167 880,200L880,480L800,480L800,200Q800,200 800,200Q800,200 800,200L160,200Q160,200 160,200Q160,200 160,200L160,680Q160,680 160,680Q160,680 160,680L680,680L680,760L600,760L600,840L320,840ZM440,600L520,600L520,480L640,480L640,400L520,400L520,280L440,280L440,400L320,400L320,480L440,480L440,600ZM160,680L160,680Q160,680 160,680Q160,680 160,680L160,200Q160,200 160,200Q160,200 160,200L160,200Q160,200 160,200Q160,200 160,200L160,680L160,680L160,680Z" /> android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round"
android:pathData="M3 5h6 M3 12h13 M3 19h13 M16 8l-3-3 3-3 M21 19V7a2 2 0 0 0-2-2h-6" />
</vector> </vector>
@@ -1,11 +1,15 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<!-- Lucide 'list-end' (lucide-static v1.72.0, ISC License) -->
<vector xmlns:android="http://schemas.android.com/apk/res/android" <vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp" android:width="24dp"
android:height="24dp" android:height="24dp"
android:tint="?attr/colorControlNormal" android:tint="?attr/colorControlNormal"
android:viewportWidth="960" android:viewportWidth="24"
android:viewportHeight="960"> android:viewportHeight="24">
<path <path
android:fillColor="@android:color/white" android:strokeColor="@android:color/white"
android:pathData="M440,600L520,600L520,480L640,480L640,400L520,400L520,280L440,280L440,400L320,400L320,480L440,480L440,600ZM320,840L320,760L160,760Q127,760 103.5,736.5Q80,713 80,680L80,200Q80,167 103.5,143.5Q127,120 160,120L800,120Q833,120 856.5,143.5Q880,167 880,200L880,680Q880,713 856.5,736.5Q833,760 800,760L640,760L640,840L320,840ZM160,680L800,680Q800,680 800,680Q800,680 800,680L800,200Q800,200 800,200Q800,200 800,200L160,200Q160,200 160,200Q160,200 160,200L160,680Q160,680 160,680Q160,680 160,680ZM160,680Q160,680 160,680Q160,680 160,680L160,200Q160,200 160,200Q160,200 160,200L160,200Q160,200 160,200Q160,200 160,200L160,680Q160,680 160,680Q160,680 160,680L160,680Z" /> android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round"
android:pathData="M16 5H3 M16 12H3 M9 19H3 M16 16l-3 3 3 3 M21 5v12a2 2 0 0 1-2 2h-6" />
</vector> </vector>
@@ -108,16 +108,38 @@
app:layout_constraintEnd_toEndOf="parent" app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@+id/playback_panel_fragment"> app:layout_constraintStart_toEndOf="@+id/playback_panel_fragment">
<TextView <LinearLayout
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal">
<com.google.android.material.button.MaterialButton
android:id="@+id/queue_shuffle"
style="@style/Widget.Auxio.Button.TextButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/lbl_shuffle"
android:visibility="gone" />
<TextView
android:layout_width="0dp"
android:layout_height="64dp" android:layout_height="64dp"
android:layout_weight="1"
android:gravity="center" android:gravity="center"
android:text="@string/lbl_queue" android:text="@string/lbl_queue"
android:textAppearance="?attr/textAppearanceLabelLargeEmphasized" android:textAppearance="?attr/textAppearanceLabelLargeEmphasized"
android:textColor="?attr/colorOnSurfaceVariant" android:textColor="?attr/colorOnSurfaceVariant" />
app:layout_constraintBottom_toBottomOf="@+id/handle"
app:layout_constraintEnd_toEndOf="@+id/handle" <com.google.android.material.button.MaterialButton
app:layout_constraintStart_toStartOf="parent" /> android:id="@+id/queue_clear"
style="@style/Widget.Auxio.Button.TextButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/action_clear"
android:visibility="gone" />
</LinearLayout>
<androidx.fragment.app.FragmentContainerView <androidx.fragment.app.FragmentContainerView
android:id="@+id/queue_fragment" android:id="@+id/queue_fragment"
+22
View File
@@ -126,6 +126,28 @@
app:layout_constraintEnd_toEndOf="@+id/queue_handle" app:layout_constraintEnd_toEndOf="@+id/queue_handle"
app:layout_constraintStart_toStartOf="parent" /> app:layout_constraintStart_toStartOf="parent" />
<com.google.android.material.button.MaterialButton
android:id="@+id/queue_shuffle"
style="@style/Widget.Auxio.Button.TextButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/lbl_shuffle"
android:visibility="gone"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.google.android.material.button.MaterialButton
android:id="@+id/queue_clear"
style="@style/Widget.Auxio.Button.TextButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/action_clear"
android:visibility="gone"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout> </androidx.constraintlayout.widget.ConstraintLayout>
<androidx.fragment.app.FragmentContainerView <androidx.fragment.app.FragmentContainerView
@@ -17,4 +17,14 @@
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" /> android:layout_height="wrap_content" />
<TextView
android:id="@+id/queue_empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="@string/lbl_queue_empty"
android:textAppearance="?attr/textAppearanceBodyLarge"
android:textColor="?attr/colorOnSurfaceVariant"
android:visibility="gone" />
</FrameLayout> </FrameLayout>
+16
View File
@@ -2,8 +2,24 @@
<navigation xmlns:android="http://schemas.android.com/apk/res/android" <navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/inner"
app:startDestination="@id/home_fragment"> app:startDestination="@id/home_fragment">
<!-- Root-level actions usable from any destination, for the Now Playing header's parent
navigation, which must work no matter which page is in front. -->
<action
android:id="@+id/show_album_globally"
app:destination="@id/album_detail_fragment" />
<action
android:id="@+id/show_artist_globally"
app:destination="@id/artist_detail_fragment" />
<action
android:id="@+id/show_genre_globally"
app:destination="@id/genre_detail_fragment" />
<action
android:id="@+id/show_playlist_globally"
app:destination="@id/playlist_detail_fragment" />
<fragment <fragment
android:id="@+id/home_fragment" android:id="@+id/home_fragment"
android:name="org.oxycblt.auxio.home.HomeFragment" android:name="org.oxycblt.auxio.home.HomeFragment"
+2
View File
@@ -123,6 +123,8 @@
<string name="lbl_shuffle">Shuffle</string> <string name="lbl_shuffle">Shuffle</string>
<string name="lbl_queue">Queue</string> <string name="lbl_queue">Queue</string>
<string name="lbl_queue_empty">Nothing queued</string>
<string name="action_clear">Clear</string>
<string name="lbl_play_next">Play next</string> <string name="lbl_play_next">Play next</string>
<string name="lbl_queue_add">Add to queue</string> <string name="lbl_queue_add">Add to queue</string>
@@ -0,0 +1,359 @@
/*
* Copyright (c) 2026 Auxio Project
* LibrarySnapshotPlaybackIntegrationTest.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.music
import android.content.Context
import androidx.media3.exoplayer.ExoPlayer
import io.mockk.coEvery
import io.mockk.every
import io.mockk.mockk
import io.mockk.spyk
import io.mockk.verify
import java.util.UUID
import java.util.concurrent.CountDownLatch
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.setMain
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertSame
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.oxycblt.auxio.image.ImageSettings
import org.oxycblt.auxio.image.covers.SettingCovers
import org.oxycblt.auxio.playback.PlaybackSettings
import org.oxycblt.auxio.playback.persist.PersistenceRepository
import org.oxycblt.auxio.playback.replaygain.ReplayGainAudioProcessor
import org.oxycblt.auxio.playback.service.ExoPlaybackStateHolder
import org.oxycblt.auxio.playback.state.DeferredPlayback
import org.oxycblt.auxio.playback.state.FakePlaybackStateHolder
import org.oxycblt.auxio.playback.state.PlaybackStateManager
import org.oxycblt.auxio.playback.state.PlaybackStateManagerImpl
import org.oxycblt.auxio.playback.state.RawQueue
import org.oxycblt.auxio.playback.state.RepeatMode
import org.oxycblt.auxio.playback.state.StateAck
import org.oxycblt.musikr.Music
import org.oxycblt.musikr.MutableLibrary
import org.oxycblt.musikr.Song
import org.oxycblt.musikr.tag.Name
import org.oxycblt.musikr.tag.ReplayGainAdjustment
/** Snapshot publication composed with the existing restoration and reconciliation boundaries. */
@OptIn(ExperimentalCoroutinesApi::class)
class LibrarySnapshotPlaybackIntegrationTest {
private lateinit var mainExecutor: ExecutorService
@Before
fun installMain() {
mainExecutor = Executors.newSingleThreadExecutor { Thread(it, "snapshot-playback-main") }
Dispatchers.setMain(mainExecutor.asCoroutineDispatcher())
}
@After
fun resetMain() {
Dispatchers.resetMain()
mainExecutor.shutdownNow()
}
@Test
fun initialDeferredRestore_isReleasedOnceByNonemptySnapshot() = runTest {
val songs = listOf(song("First"), song("Current"))
val library = library(songs)
val repository = scanBoundaryRepository(library)
val playback = PlaybackStateManagerImpl()
val fake = FakePlaybackStateHolder()
val persistence = mockk<PersistenceRepository>()
val reads = AtomicInteger()
coEvery { persistence.readState() } answers {
reads.incrementAndGet()
savedState(songs, currentIndex = 1)
}
val holder =
spyk(
ExoPlaybackStateHolder(
mockk<Context>(),
mockk<ExoPlayer>(),
playback,
persistence,
mockk<PlaybackSettings>(),
mockk(),
mockk<ReplayGainAudioProcessor>(),
repository,
mockk<ImageSettings>(),
)
)
every { holder.parent } answers { fake.parent }
every { holder.resolveQueue() } answers { fake.resolveQueue() }
every { holder.applySavedState(any(), any(), any(), any(), any()) } answers {
fake.applySavedState(
firstArg(),
secondArg(),
thirdArg(),
arg(3),
ack = null,
)
arg<StateAck.NewPlayback?>(4)?.let { playback.ack(holder, it) }
}
playback.registerStateHolder(holder)
repository.addUpdateListener(holder)
val snapshotCallbacks = AtomicInteger()
repository.addUpdateListener(
object : MusicRepository.UpdateListener {
override fun onMusicChanges(changes: MusicRepository.Changes) {
if (changes.deviceLibrary && repository.library === library) {
snapshotCallbacks.incrementAndGet()
}
}
}
)
val restored = CountDownLatch(1)
playback.addListener(
object : PlaybackStateManager.Listener {
override fun onNewPlayback(
parent: org.oxycblt.musikr.MusicParent?,
queue: List<Song>,
index: Int,
isShuffled: Boolean,
) {
restored.countDown()
}
}
)
playback.playDeferred(DeferredPlayback.RestoreState(play = false, fallback = null))
assertTrue(fake.rawQueue.heap.isEmpty())
repository.index(mockk(), withCache = true)
assertEquals(1, snapshotCallbacks.get())
val released = restored.await(5, TimeUnit.SECONDS)
assertTrue(
"Snapshot did not release deferred restoration; reads=${reads.get()}, " +
"rawQueue=${fake.rawQueue.heap.size}, current=${playback.currentSong}",
released,
)
assertEquals(1, reads.get())
verify(exactly = 1) {
holder.applySavedState(
null,
RawQueue(songs, emptyList(), heapIndex = 1),
positionMs = 4_321L,
repeatMode = RepeatMode.NONE,
ack = StateAck.NewPlayback,
)
}
assertEquals(songs, fake.rawQueue.heap)
assertEquals(songs, playback.queue)
assertSame(songs[1], playback.currentSong)
}
@Test
fun unchangedFinalGraph_retainsQueueCurrentAndUIDs() {
val songs = listOf(song("First"), song("Current"), song("Last"))
val playback = PlaybackStateManagerImpl()
val holder = FakePlaybackStateHolder()
holder.manager = playback
playback.registerStateHolder(holder)
val restorationEvents = AtomicInteger()
playback.addListener(
object : PlaybackStateManager.Listener {
override fun onNewPlayback(
parent: org.oxycblt.musikr.MusicParent?,
queue: List<Song>,
index: Int,
isShuffled: Boolean,
) {
restorationEvents.incrementAndGet()
}
}
)
playback.applySavedState(savedState(songs, currentIndex = 1), destructive = false)
val originalQueue = holder.rawQueue
assertEquals(2, restorationEvents.get())
org.oxycblt.auxio.music.service.IndexingHolder.reconcilePlaybackState(
playback,
library(songs),
mockk<MusicRepository>(),
)
assertEquals(4, restorationEvents.get())
assertEquals(originalQueue, holder.rawQueue)
assertEquals(songs, playback.queue)
assertEquals(songs.map { it.uid }, playback.queue.map { it.uid })
assertSame(songs[0], holder.rawQueue.heap[0])
assertSame(songs[1], playback.currentSong)
}
@Test
fun finalGraph_remapsSongsParentAndDeckToMatchingUIDs() {
val oldSongs = listOf(song("First"), song("Current"), song("Queued"), song("Last"))
val oldParent = parent()
val freshParent = parent(oldParent.uid)
val freshSongs = oldSongs.map { song("Fresh ${it.name.raw}", it.uid) }
val playback = PlaybackStateManagerImpl()
val holder = FakePlaybackStateHolder()
holder.manager = playback
playback.registerStateHolder(holder)
playback.applySavedState(
savedState(
oldSongs,
currentIndex = 1,
parent = oldParent,
deck = oldSongs.subList(1, 3),
deckCurrent = true,
),
destructive = false,
)
assertEquals(listOf(oldSongs[2]), playback.deck)
assertSame(oldSongs[1], playback.deckCurrent)
val repository = mockk<MusicRepository>()
every { repository.find(oldParent.uid) } returns freshParent
org.oxycblt.auxio.music.service.IndexingHolder.reconcilePlaybackState(
playback,
library(freshSongs),
repository,
)
assertEquals(freshSongs, holder.rawQueue.heap)
assertEquals(oldSongs.map { it.uid }, playback.queue.map { it.uid })
assertSame(freshSongs[1], playback.currentSong)
assertSame(freshParent, playback.parent)
assertEquals(listOf(freshSongs[2]), playback.deck)
assertSame(freshSongs[1], playback.deckCurrent)
holder.rawQueue.heap.forEachIndexed { index, song -> assertSame(freshSongs[index], song) }
}
@Test
fun missingCurrentSong_resetsDefensivelyAndClearsDeck() {
val oldSongs = listOf(song("First"), song("Removed current"), song("Queued"), song("Last"))
val playback = PlaybackStateManagerImpl()
val holder = FakePlaybackStateHolder()
holder.manager = playback
playback.registerStateHolder(holder)
playback.applySavedState(
savedState(
oldSongs,
currentIndex = 1,
deck = oldSongs.subList(1, 3),
deckCurrent = true,
),
destructive = false,
)
assertSame(oldSongs[1], playback.currentSong)
assertEquals(listOf(oldSongs[2]), playback.deck)
assertSame(oldSongs[1], playback.deckCurrent)
val finalSongs = oldSongs.filter { it !== oldSongs[1] }.map { song("Fresh", it.uid) }
org.oxycblt.auxio.music.service.IndexingHolder.reconcilePlaybackState(
playback,
library(finalSongs),
mockk<MusicRepository>(),
)
assertTrue(holder.rawQueue.heap.isEmpty())
assertTrue(playback.queue.isEmpty())
assertNull(playback.currentSong)
assertTrue(playback.deck.isEmpty())
assertNull(playback.deckCurrent)
}
private fun song(
label: String,
uid: Music.UID = requireNotNull(Music.UID.fromString("uas${UUID.randomUUID()}")),
): Song {
val song = mockk<Song>()
every { song.uid } returns uid
val name = mockk<Name.Known>()
every { name.raw } returns label
every { song.name } returns name
every { song.replayGainAdjustment } returns ReplayGainAdjustment(null, null)
return song
}
private fun library(songs: List<Song>): MutableLibrary {
val library = mockk<MutableLibrary>()
every { library.empty() } returns songs.isEmpty()
every { library.songs } returns songs.toSet()
every { library.playlists } returns emptySet()
every { library.findSong(any()) } answers
{
songs.find { it.uid == firstArg<Music.UID>() }
}
return library
}
private fun parent(
uid: Music.UID = requireNotNull(Music.UID.fromString("uaa${UUID.randomUUID()}"))
): org.oxycblt.musikr.MusicParent {
val parent = mockk<org.oxycblt.musikr.MusicParent>()
every { parent.uid } returns uid
return parent
}
private fun savedState(
songs: List<Song>,
currentIndex: Int,
parent: org.oxycblt.musikr.MusicParent? = null,
deck: List<Song> = emptyList(),
deckCurrent: Boolean = false,
) =
PlaybackStateManager.SavedState(
positionMs = 4_321L,
repeatMode = RepeatMode.NONE,
parent = parent,
heap = songs,
shuffledMapping = emptyList(),
deck = deck,
deckCurrent = deckCurrent,
index = currentIndex,
songUid = songs[currentIndex].uid,
)
private fun scanBoundaryRepository(library: MutableLibrary): MusicRepositoryImpl {
val settings = mockk<MusicSettings>()
every { settings.separators } returns ""
every { settings.intelligentSorting } returns true
every { settings.revision } returns null
val covers = mockk<SettingCovers>()
coEvery { covers.mutate(any(), any()) } throws
IllegalStateException("Expected post-snapshot indexing boundary")
return MusicRepositoryImpl(
mockk(),
mockk(),
mockk(),
covers,
settings,
UnarySnapshotRestorer(library),
)
}
}
private class UnarySnapshotRestorer(private val library: MutableLibrary) : SnapshotRestorer {
override fun start(): SnapshotRestoration = SharedSnapshotRestoration { library }
}
@@ -0,0 +1,269 @@
/*
* Copyright (c) 2026 Auxio Project
* LibrarySnapshotPublicationTest.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.music
import android.content.Context
import io.mockk.Runs
import io.mockk.coEvery
import io.mockk.every
import io.mockk.just
import io.mockk.justRun
import io.mockk.mockk
import io.mockk.mockkObject
import io.mockk.unmockkObject
import java.io.IOException
import java.util.Collections
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicInteger
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.setMain
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertSame
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.oxycblt.auxio.image.covers.SettingCovers
import org.oxycblt.auxio.music.locations.LocationMode
import org.oxycblt.musikr.Config
import org.oxycblt.musikr.Library
import org.oxycblt.musikr.LibraryResult
import org.oxycblt.musikr.MutableLibrary
import org.oxycblt.musikr.Musikr
import org.oxycblt.musikr.Song
import org.oxycblt.musikr.covers.Cover
import org.oxycblt.musikr.covers.MutableCovers
import org.oxycblt.musikr.fs.saf.SAF
import org.oxycblt.musikr.tag.Name
import org.oxycblt.musikr.tag.ReplayGainAdjustment
@OptIn(ExperimentalCoroutinesApi::class)
class LibrarySnapshotPublicationTest {
private lateinit var mainExecutor: ExecutorService
@Before
fun installMain() {
mainExecutor = Executors.newSingleThreadExecutor { Thread(it, "snapshot-test-main") }
Dispatchers.setMain(mainExecutor.asCoroutineDispatcher())
}
@After
fun resetMain() {
Dispatchers.resetMain()
mainExecutor.shutdownNow()
}
@Test
fun validNonemptySnapshot_publishesBeforeRepositoryIndexing() = runTest {
val cached = library(empty = false)
val scanCalls = AtomicInteger()
val repository =
scanBoundaryRepository(
TestSnapshotRestorer(SharedSnapshotRestoration { cached }),
scanCalls,
)
val emissions = mutableListOf<Int>()
repository.addUpdateListener(
object : MusicRepository.UpdateListener {
override fun onMusicChanges(changes: MusicRepository.Changes) {
emissions += scanCalls.get()
}
}
)
emissions.clear()
repository.index(mockk(), withCache = true)
assertEquals(listOf(0), emissions)
assertSame(cached, repository.library)
}
@Test
fun absentCorruptOrEmptySnapshot_emitsNoLibraryAndStillIndexes() = runTest {
val restorations =
listOf(
object : SnapshotRestoration {
override suspend fun await(): MutableLibrary? = null
},
SharedSnapshotRestoration { throw IOException("Forced corrupt snapshot") },
SharedSnapshotRestoration { library(empty = true) },
)
for (restoration in restorations) {
val scanCalls = AtomicInteger()
val repository =
scanBoundaryRepository(TestSnapshotRestorer(restoration), scanCalls)
val emissions = AtomicInteger()
repository.addUpdateListener(
object : MusicRepository.UpdateListener {
override fun onMusicChanges(changes: MusicRepository.Changes) {
emissions.incrementAndGet()
}
}
)
emissions.set(0)
repository.index(mockk(), withCache = true)
assertNull(repository.library)
assertEquals(0, emissions.get())
assertEquals(1, scanCalls.get())
}
}
@Test
fun snapshotChange_deliversUpdateListenerOnMain() = runTest {
val repository =
scanBoundaryRepository(
TestSnapshotRestorer(
SharedSnapshotRestoration { library(empty = false) }
),
AtomicInteger(),
)
val callbackThreads = Collections.synchronizedList(mutableListOf<String>())
repository.addUpdateListener(
object : MusicRepository.UpdateListener {
override fun onMusicChanges(changes: MusicRepository.Changes) {
callbackThreads += Thread.currentThread().name
}
}
)
callbackThreads.clear()
repository.index(mockk(), withCache = true)
assertEquals(listOf("snapshot-test-main"), callbackThreads)
}
@Test
fun finalFreshResult_isPublishedCapturedAndCaptureFailureIsIsolated() = runTest {
for (failure in listOf<IOException?>(null, IOException("Forced capture failure"))) {
val cached = library(empty = false)
val fresh = library(empty = false)
val restorer =
TestSnapshotRestorer(SharedSnapshotRestoration { cached }).apply {
captureFailure = failure
}
val context = mockk<Context>()
every { context.applicationContext } returns context
every { context.contentResolver } returns mockk()
val settings = mockk<MusicSettings>()
every { settings.separators } returns ",;"
every { settings.intelligentSorting } returns true
every { settings.revision } returns null
justRun { settings.revision = any() }
every { settings.locationMode } returns LocationMode.SAF
every { settings.safQuery } returns
SAF.Query(emptyList(), emptyList(), withHidden = false, multithread = false)
val covers = mockk<SettingCovers>()
coEvery { covers.mutate(context, any()) } returns mockk<MutableCovers<out Cover>>()
val repository =
MusicRepositoryImpl(
context,
mockk(),
mockk(),
covers,
settings,
restorer,
)
val emitted = mutableListOf<MutableLibrary?>()
repository.addUpdateListener(
object : MusicRepository.UpdateListener {
override fun onMusicChanges(changes: MusicRepository.Changes) {
emitted += repository.library
}
}
)
emitted.clear()
mockkObject(Musikr.Companion)
try {
val result = mockk<LibraryResult>()
every { result.library } returns fresh
coEvery { result.cleanup() } just Runs
val music = mockk<Musikr>()
coEvery { music.run(any()) } returns result
every { Musikr.new(any(), any()) } returns music
repository.index(mockk(), withCache = true)
} finally {
unmockkObject(Musikr.Companion)
}
assertEquals(listOf(cached, fresh), emitted)
assertSame(fresh, repository.library)
assertEquals(listOf(fresh), restorer.captures.map { it.first })
assertTrue(repository.indexingState is IndexingState.Completed)
assertNull((repository.indexingState as IndexingState.Completed).error)
}
}
private fun scanBoundaryRepository(
restorer: SnapshotRestorer,
scanCalls: AtomicInteger,
): MusicRepositoryImpl {
val settings = mockk<MusicSettings>()
every { settings.separators } answers {
scanCalls.incrementAndGet()
""
}
every { settings.intelligentSorting } returns true
every { settings.revision } returns null
val covers = mockk<SettingCovers>()
coEvery { covers.mutate(any(), any()) } throws
IllegalStateException("Expected test indexing boundary")
return MusicRepositoryImpl(mockk(), mockk(), mockk(), covers, settings, restorer)
}
private fun library(empty: Boolean): MutableLibrary {
val library = mockk<MutableLibrary>()
every { library.empty() } returns empty
if (!empty) {
val name = mockk<Name.Known>()
every { name.raw } returns "Snapshot Song"
val song = mockk<Song>()
every { song.name } returns name
every { song.replayGainAdjustment } returns ReplayGainAdjustment(null, null)
every { library.songs } returns setOf(song)
} else {
every { library.songs } returns emptySet()
}
every { library.playlists } returns emptySet()
return library
}
private class TestSnapshotRestorer(
private val restoration: SnapshotRestoration
) : SnapshotRestorer {
val captures = mutableListOf<Pair<Library, Config>>()
var captureFailure: Exception? = null
override fun start() = restoration
override suspend fun capture(library: Library, config: Config) {
captures += library to config
captureFailure?.let { throw it }
}
}
}
@@ -0,0 +1,208 @@
/*
* Copyright (c) 2026 Auxio Project
* LibrarySnapshotRestoreConcurrencyTest.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.music
import io.mockk.coEvery
import io.mockk.every
import io.mockk.mockk
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicReference
import kotlin.coroutines.ContinuationInterceptor
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.async
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.setMain
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertSame
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.oxycblt.auxio.image.covers.SettingCovers
import org.oxycblt.musikr.MutableLibrary
@OptIn(ExperimentalCoroutinesApi::class)
class LibrarySnapshotRestoreConcurrencyTest {
@Before
fun installMainDispatcher() {
Dispatchers.setMain(UnconfinedTestDispatcher())
}
@After
fun resetMainDispatcher() {
Dispatchers.resetMain()
}
@Test
fun repositoryCreation_startsRestorationOffMain() {
val dispatcher = AtomicReference<ContinuationInterceptor?>()
val restoration =
SharedSnapshotRestoration {
dispatcher.set(currentCoroutineContext()[ContinuationInterceptor])
null
}
restorationsAwait(restoration)
assertSame(Dispatchers.IO, dispatcher.get())
val restorer = TestSnapshotRestorer(restoration)
repository(restorer)
assertEquals(1, restorer.starts)
}
@Test
fun repeatedIndexingCalls_shareOneRestorationAttempt() = runTest {
val attempts = AtomicInteger()
val scanCalls = AtomicInteger()
val started = CompletableDeferred<Unit>()
val release = CompletableDeferred<MutableLibrary?>()
val restoration =
SharedSnapshotRestoration {
attempts.incrementAndGet()
started.complete(Unit)
release.await()
}
val restorer = TestSnapshotRestorer(restoration)
val repository = scanningRepository(restorer, scanCalls)
val worker = mockk<MusicRepository.IndexingWorker>()
val first = async { repository.index(worker, withCache = true) }
val second = async { repository.index(worker, withCache = true) }
started.await()
assertEquals(0, scanCalls.get())
release.complete(null)
first.await()
second.await()
assertEquals(1, attempts.get())
assertEquals(1, restorer.starts)
}
@Test
fun indexing_awaitsRestorationBeforeReadingIndexConfiguration() = runTest {
val entered = CompletableDeferred<Unit>()
val release = CompletableDeferred<MutableLibrary?>()
val restoration =
object : SnapshotRestoration {
override suspend fun await(): MutableLibrary? {
entered.complete(Unit)
return release.await()
}
}
val scanCalls = AtomicInteger()
val repository = scanningRepository(TestSnapshotRestorer(restoration), scanCalls)
val worker = mockk<MusicRepository.IndexingWorker>()
val indexing = async { repository.index(worker, withCache = true) }
entered.await()
assertEquals(0, scanCalls.get())
release.complete(null)
indexing.await()
assertEquals(1, scanCalls.get())
}
@Test
fun cancellingIndexing_doesNotCancelIndependentRestoration() = runTest {
val attempts = AtomicInteger()
val finished = AtomicBoolean()
val started = CompletableDeferred<Unit>()
val release = CompletableDeferred<MutableLibrary?>()
val restoration =
SharedSnapshotRestoration {
attempts.incrementAndGet()
started.complete(Unit)
release.await()
finished.set(true)
null
}
val scanCalls = AtomicInteger()
val repository = scanningRepository(TestSnapshotRestorer(restoration), scanCalls)
val worker = mockk<MusicRepository.IndexingWorker>()
val indexing = async { repository.index(worker, withCache = true) }
started.await()
indexing.cancel()
indexing.join()
assertTrue(indexing.isCancelled)
assertEquals(0, scanCalls.get())
assertFalse(finished.get())
release.complete(null)
restoration.await()
assertTrue(finished.get())
assertEquals(1, attempts.get())
}
private fun scanningRepository(
restorer: SnapshotRestorer,
scanCalls: AtomicInteger,
): MusicRepositoryImpl {
val settings = mockk<MusicSettings>()
every { settings.separators } answers {
scanCalls.incrementAndGet()
""
}
every { settings.intelligentSorting } returns true
every { settings.revision } returns null
every { settings.useFileTreeCache } returns false
val covers = mockk<SettingCovers>()
coEvery { covers.mutate(any(), any()) } throws
IllegalStateException("Expected test indexing boundary")
return MusicRepositoryImpl(mockk(), mockk(), mockk(), covers, settings, restorer)
}
private fun restorationsAwait(restoration: SnapshotRestoration) {
runBlocking { restoration.await() }
}
private fun repository(restorer: SnapshotRestorer) =
MusicRepositoryImpl(
mockk(),
mockk(),
mockk(),
mockk(),
mockk(),
restorer,
)
private class TestSnapshotRestorer(
private val restoration: SnapshotRestoration
) : SnapshotRestorer {
var starts = 0
private set
override fun start(): SnapshotRestoration {
starts += 1
return restoration
}
}
}
@@ -0,0 +1,103 @@
/*
* Copyright (c) 2026 Auxio Project
* DeckRowDiffTest.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.queue
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
import org.oxycblt.auxio.list.adapter.UpdateInstructions
import org.oxycblt.auxio.playback.state.fakeSong
/**
* The queue drawer renders deck rows; every update must carry the minimal [UpdateInstructions]
* for the change, or the list flashes (full replaces) and ghosts (desynced drags). See the D9
* device round.
*/
class DeckRowDiffTest {
@Test
fun `identical rows produce no instruction`() {
val rows = listOf(fakeSong(), fakeSong())
assertNull(diffDeckRows(rows, rows.toList()))
}
@Test
fun `appending rows produces an Add`() {
val old = listOf(fakeSong(), fakeSong(), fakeSong())
val new = old + fakeSong() + fakeSong()
assertEquals(UpdateInstructions.Add(at = 3, size = 2), diffDeckRows(old, new))
}
@Test
fun `the deck advancing drops row 0 with a Remove`() {
val old = listOf(fakeSong(), fakeSong(), fakeSong())
val new = old.drop(1)
assertEquals(UpdateInstructions.Remove(at = 0, size = 1), diffDeckRows(old, new))
}
@Test
fun `removing an interior row produces a Remove`() {
val old = listOf(fakeSong(), fakeSong(), fakeSong())
val new = listOf(old[0], old[2])
assertEquals(UpdateInstructions.Remove(at = 1, size = 1), diffDeckRows(old, new))
}
@Test
fun `emptying the rows produces a Remove`() {
val old = listOf(fakeSong(), fakeSong())
assertEquals(UpdateInstructions.Remove(at = 0, size = 2), diffDeckRows(old, emptyList()))
}
@Test
fun `an end drag produces a Move`() {
val old = listOf(fakeSong(), fakeSong(), fakeSong())
val new = listOf(old[1], old[2], old[0])
assertEquals(UpdateInstructions.Move(from = 0, to = 2), diffDeckRows(old, new))
}
@Test
fun `an adjacent drag produces a Move`() {
val old = listOf(fakeSong(), fakeSong(), fakeSong())
val new = listOf(old[0], old[2], old[1])
assertEquals(UpdateInstructions.Move(from = 1, to = 2), diffDeckRows(old, new))
}
@Test
fun `a deck shuffle permutation produces a Replace from the first divergence`() {
// A multi-element permutation is no single move; the drawer must re-render the
// shuffled region wholesale, which is coherent for a deliberate shuffle.
val old = listOf(fakeSong(), fakeSong(), fakeSong())
val new = old.reversed()
assertEquals(UpdateInstructions.Replace(from = 0), diffDeckRows(old, new))
}
@Test
fun `a replacement produces a Replace from the first divergence`() {
val old = listOf(fakeSong(), fakeSong(), fakeSong())
val new = listOf(old[0], fakeSong(), old[2])
assertEquals(UpdateInstructions.Replace(from = 1), diffDeckRows(old, new))
}
@Test
fun `a wholesale change produces a Replace`() {
val old = listOf(fakeSong(), fakeSong())
val new = listOf(fakeSong(), fakeSong(), fakeSong())
assertEquals(UpdateInstructions.Replace(from = 0), diffDeckRows(old, new))
}
}
@@ -47,6 +47,9 @@ class FakePlaybackStateHolder : PlaybackStateHolder {
/** Every [StateAck.PlayNext] receipt handed to this holder, in order. */ /** Every [StateAck.PlayNext] receipt handed to this holder, in order. */
val insertions = mutableListOf<StateAck.PlayNext>() val insertions = mutableListOf<StateAck.PlayNext>()
/** Every [StateAck.ShuffleDeck] receipt handed to this holder, in order. */
val shuffles = mutableListOf<StateAck.ShuffleDeck>()
var rawQueue = RawQueue.nil() var rawQueue = RawQueue.nil()
private set private set
@@ -155,7 +158,10 @@ class FakePlaybackStateHolder : PlaybackStateHolder {
} }
} }
override fun goto(index: Int) {} override fun goto(index: Int) {
// A jump is an advance to the position, as the real holder's seek is.
moveTo(index)
}
override fun addToQueue(songs: List<Song>, ack: StateAck.AddToQueue) { override fun addToQueue(songs: List<Song>, ack: StateAck.AddToQueue) {
insertAt(ack.at, songs) insertAt(ack.at, songs)
@@ -222,6 +228,18 @@ class FakePlaybackStateHolder : PlaybackStateHolder {
manager?.ack(this, StateAck.QueueReordered) manager?.ack(this, StateAck.QueueReordered)
} }
override fun shuffleDeck(deckSize: Int, ack: StateAck.ShuffleDeck) {
shuffles += ack
// The waiting deck block directly behind the current song reverses, as a stand-in
// permutation. The playback order pins that block in place, so the resolved order
// follows the new physical order.
val current = rawQueue.heapIndex
val heap = rawQueue.heap.toMutableList()
heap.subList(current + 1, current + 1 + deckSize).reverse()
rawQueue = RawQueue(heap, rawQueue.shuffledMapping, rawQueue.heapIndex)
manager?.ack(this, ack)
}
override fun handleDeferred(action: DeferredPlayback) = false override fun handleDeferred(action: DeferredPlayback) = false
override fun applySavedState( override fun applySavedState(
@@ -239,7 +257,10 @@ class FakePlaybackStateHolder : PlaybackStateHolder {
override fun endSession() {} override fun endSession() {}
override fun reset(ack: StateAck.NewPlayback) {} override fun reset(ack: StateAck.NewPlayback) {
rawQueue = RawQueue.nil()
manager?.ack(this, ack)
}
} }
/** /**
@@ -19,10 +19,294 @@
package org.oxycblt.auxio.playback.state package org.oxycblt.auxio.playback.state
import org.junit.Assert.assertEquals import org.junit.Assert.assertEquals
import org.oxycblt.musikr.Song
import org.junit.Assert.assertSame import org.junit.Assert.assertSame
import org.junit.Test import org.junit.Test
class PlaybackStateManagerImplTest { class PlaybackStateManagerImplTest {
/**
* Regression (D9): listeners must observe the final deck state at notification time. The
* deck bookkeeping used to run after notifying, leaving the UI one update behind and the
* playing row unhighlighted.
*/
@Test
fun `listeners observe the final deck state at notification time`() {
val manager = PlaybackStateManagerImpl()
val holder = FakePlaybackStateHolder()
holder.manager = manager
manager.registerStateHolder(holder)
// Record the deck state observed at each callback.
val observedDecks = mutableListOf<List<Song>>()
val observedCurrent = mutableListOf<Boolean>()
manager.addListener(
object : PlaybackStateManager.Listener {
override fun onQueueChanged(queue: List<Song>, index: Int, change: QueueChange) {
observedDecks += manager.deck.toList()
}
override fun onIndexMoved(index: Int) {
observedCurrent += manager.deckCurrent != null
}
}
)
// Playing index 2 of a 10-song queue; queue two songs in separate actions.
val heap = List(10) { fakeSong() }
manager.play(PlaybackCommandFactoryImpl.PlaybackCommandImpl(heap[2], null, heap, false))
manager.playAfter(listOf(fakeSong()))
manager.playAfter(listOf(fakeSong()))
// The second action's callback observes both deck entries, not the pre-append state.
assertEquals(2, observedDecks.last().size)
// Entering the deck: the callback observes the playing song as deck-sourced.
holder.moveTo(3)
assertEquals(true, observedCurrent.last())
}
/**
* Drag-reordering deck rows reorders the waiting entries; drags involving the playing row
* are refused.
*/
@Test
fun `moveDeckItems reorders waiting drawer rows`() {
val manager = PlaybackStateManagerImpl()
val holder = FakePlaybackStateHolder()
holder.manager = manager
manager.registerStateHolder(holder)
// Playing index 2 of a 10-song queue; deck of three songs.
val heap = List(10) { fakeSong() }
manager.play(PlaybackCommandFactoryImpl.PlaybackCommandImpl(heap[2], null, heap, false))
manager.playAfter(listOf(fakeSong(), fakeSong(), fakeSong()))
// Drag the first waiting row to the end: the deck reorders.
val a = manager.queue[3]
val b = manager.queue[4]
val c = manager.queue[5]
manager.moveDeckItems(0, 2)
assertEquals(b, manager.queue[3])
assertEquals(c, manager.queue[4])
assertEquals(a, manager.queue[5])
// Enter the deck: drags involving the playing row 0 are refused.
holder.moveTo(3)
manager.moveDeckItems(0, 1)
assertEquals(c, manager.queue[4])
assertEquals(a, manager.queue[5])
manager.moveDeckItems(1, 0)
assertEquals(c, manager.queue[4])
assertEquals(a, manager.queue[5])
// A waiting-to-waiting drag still works.
manager.moveDeckItems(1, 2)
assertEquals(a, manager.queue[4])
assertEquals(c, manager.queue[5])
}
/**
* Swipe-removing a waiting deck row deletes that entry only; swiping the playing row or an
* out-of-range row is refused.
*/
@Test
fun `removeDeckItem removes a waiting drawer row`() {
val manager = PlaybackStateManagerImpl()
val holder = FakePlaybackStateHolder()
holder.manager = manager
manager.registerStateHolder(holder)
// Playing index 2 of a 10-song queue; deck of three songs.
val heap = List(10) { fakeSong() }
manager.play(PlaybackCommandFactoryImpl.PlaybackCommandImpl(heap[2], null, heap, false))
manager.playAfter(listOf(fakeSong(), fakeSong(), fakeSong()))
// Remove the middle waiting row: the others survive in order.
val first = manager.queue[3]
val last = manager.queue[5]
manager.removeDeckItem(1)
assertEquals(12, manager.queue.size)
assertEquals(first, manager.queue[3])
assertEquals(last, manager.queue[4])
// Enter the deck: the playing row cannot be swiped away.
holder.moveTo(3)
val playing = manager.currentSong
manager.removeDeckItem(0)
assertEquals(12, manager.queue.size)
assertEquals(playing, manager.currentSong)
// The remaining waiting row (now row 1) is still removable, leaving the heap directly
// behind the playing song.
manager.removeDeckItem(1)
assertEquals(11, manager.queue.size)
assertEquals(playing, manager.currentSong)
assertEquals(heap[3], manager.queue[4])
// Out-of-range rows are refused.
manager.removeDeckItem(3)
assertEquals(11, manager.queue.size)
}
/**
* Tapping a deck row plays it immediately in drawer-row coordinates: row 0 restarts the
* playing deck song; a waiting row pulls the song out of line and plays it, retaining the
* rest of the queue. A displaced deck song drains; a displaced heap song passes by behind
* the playhead, the heap resuming at its successor once the queue drains.
*/
@Test
fun `gotoDeck plays a drawer row`() {
val manager = PlaybackStateManagerImpl()
val holder = FakePlaybackStateHolder()
holder.manager = manager
manager.registerStateHolder(holder)
// Playing index 2 of a 10-song queue; deck of three songs.
val heap = List(10) { fakeSong() }
manager.play(PlaybackCommandFactoryImpl.PlaybackCommandImpl(heap[2], null, heap, false))
manager.playAfter(listOf(fakeSong(), fakeSong(), fakeSong()))
// Enter the first deck song: row 0 = playing, rows 1-2 = waiting.
holder.moveTo(3)
val playing = manager.currentSong
// Row 0 restarts the playing song: no movement, no drain.
manager.gotoDeck(0)
assertEquals(playing, manager.currentSong)
assertEquals(13, manager.queue.size)
// Tapping the last waiting row: the displaced playing deck song drains, the tapped
// song plays, and the skipped waiting entry keeps its place.
val tapped = manager.queue[5]
val skipped = manager.queue[4]
manager.gotoDeck(2)
assertEquals(12, manager.queue.size)
assertEquals(tapped, manager.currentSong)
assertEquals(skipped, manager.queue[4])
// Playing the queue out resumes the heap after the interrupted song.
holder.advanceToNext()
holder.advanceToNext()
assertEquals(heap[3], manager.currentSong)
assertEquals(10, manager.queue.size)
// With a heap song playing, tapping a waiting row keeps everything: the interrupted
// heap song passes by behind the playhead, and the waiting entries keep their order.
manager.playAfter(listOf(fakeSong(), fakeSong(), fakeSong()))
val tappedAgain = manager.queue[5]
val firstWaiting = manager.queue[4]
val lastWaiting = manager.queue[6]
manager.gotoDeck(1)
assertEquals(13, manager.queue.size)
assertEquals(tappedAgain, manager.currentSong)
assertEquals(heap[3], manager.queue[3])
assertEquals(firstWaiting, manager.queue[5])
assertEquals(lastWaiting, manager.queue[6])
// The queue drains in order and the heap resumes after the interrupted song.
holder.advanceToNext()
holder.advanceToNext()
holder.advanceToNext()
assertEquals(heap[4], manager.currentSong)
assertEquals(10, manager.queue.size)
// Out-of-range rows do nothing.
manager.gotoDeck(9)
assertEquals(heap[4], manager.currentSong)
assertEquals(10, manager.queue.size)
}
/**
* Clearing the queue drops the waiting deck entries from the timeline; a queue-sourced
* current song keeps playing and drains normally afterwards.
*/
@Test
fun `clearing the queue drops the waiting deck entries`() {
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 heap = List(10) { fakeSong() }
manager.play(PlaybackCommandFactoryImpl.PlaybackCommandImpl(heap[2], null, heap, false))
manager.playAfter(listOf(fakeSong(), fakeSong()))
// Clear: the deck block leaves the timeline.
manager.clearQueue()
assertEquals(10, manager.queue.size)
assertEquals(heap[2], manager.currentSong)
// Queueing again lands directly behind the current song — no phantom boundary.
manager.playAfter(listOf(fakeSong()))
assertEquals(11, manager.queue.size)
assertEquals(StateAck.PlayNext(at = 3, size = 1), holder.insertions.last())
// Enter the deck song; clearing with nothing waiting is a no-op for the playing song.
holder.moveTo(3)
val deckSong = manager.currentSong
manager.clearQueue()
assertEquals(11, manager.queue.size)
assertEquals(deckSong, manager.currentSong)
// It drains normally when playback leaves it: the heap resumes.
holder.advanceToNext()
assertEquals(10, manager.queue.size)
assertEquals(heap[3], manager.currentSong)
}
/**
* Shuffle: shuffling the deck permutes the waiting entries in place — the playing row,
* the heap, and the deck size are untouched, and listeners observe the final state.
*/
@Test
fun `shuffleDeck permutes the waiting deck entries in place`() {
val manager = PlaybackStateManagerImpl()
val holder = FakePlaybackStateHolder()
holder.manager = manager
manager.registerStateHolder(holder)
// Record the deck state observed at each callback.
val observedDecks = mutableListOf<List<Song>>()
manager.addListener(
object : PlaybackStateManager.Listener {
override fun onQueueChanged(queue: List<Song>, index: Int, change: QueueChange) {
observedDecks += manager.deck.toList()
}
}
)
// Playing index 2 of a 10-song queue.
val heap = List(10) { fakeSong() }
manager.play(PlaybackCommandFactoryImpl.PlaybackCommandImpl(heap[2], null, heap, false))
// Deck of 3 songs occupies positions 3..5.
val deckBefore = List(3) { fakeSong() }
manager.playAfter(deckBefore)
val queueBefore = manager.queue.toList()
manager.shuffleDeck()
// The holder saw exactly one shuffle receipt.
assertEquals(1, holder.shuffles.size)
// The same waiting entries, possibly reordered: a permutation, not a replacement.
assertEquals(3, manager.deck.size)
assertEquals(deckBefore.map { it.uid }.toSet(), manager.deck.map { it.uid }.toSet())
// The deck mirrors the physical block behind the current song; the heap is untouched.
assertEquals(queueBefore.size, manager.queue.size)
assertEquals(queueBefore.subList(0, 3), manager.queue.subList(0, 3))
assertEquals(queueBefore.subList(6, 13), manager.queue.subList(6, 13))
assertEquals(manager.queue.subList(3, 6).toList(), manager.deck.toList())
// The playing song is heap-sourced here; no playing deck song exists.
assertEquals(null, manager.deckCurrent)
// The callback observed the post-shuffle deck, not a stale one.
assertEquals(manager.deck.toList(), observedDecks.last())
}
/** /**
* Persistence: a deck song missing from the library on restore drops only itself; the * 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. * rest of the deck survives, matching the heap's own realignment.
+2 -4
View File
@@ -85,12 +85,10 @@ dependencies {
tasks.register("assembleTaglib", Exec, { tasks.register("assembleTaglib", Exec, {
def jniDir = "$projectDir/src/main/cpp" def jniDir = "$projectDir/src/main/cpp"
def libs = new File("$jniDir/taglib/pkg") def libs = new File("$jniDir/taglib/pkg")
if (libs.exists()) {
commandLine "true"
return
}
def ndkDir = androidComponents.sdkComponents.ndkDirectory.get().asFile def ndkDir = androidComponents.sdkComponents.ndkDirectory.get().asFile
commandLine "sh", "-c", "$jniDir/build_taglib.sh $jniDir $ndkDir" commandLine "sh", "-c", "$jniDir/build_taglib.sh $jniDir $ndkDir"
onlyIf { !libs.exists() }
mustRunAfter(tasks.named("clean"))
}) })
afterEvaluate { afterEvaluate {
+11 -3
View File
@@ -32,7 +32,7 @@
#include "JByteArrayRef.h" #include "JByteArrayRef.h"
JMetadataBuilder::JMetadataBuilder(JNIEnv *env) : env(env), id3v2(env), xiph( JMetadataBuilder::JMetadataBuilder(JNIEnv *env) : env(env), id3v2(env), xiph(
env), mp4(env), cover(), properties(nullptr) { env), mp4(env), ape(env), cover(), properties(nullptr) {
} }
void JMetadataBuilder::setMimeType(TagLib::String type) { void JMetadataBuilder::setMimeType(TagLib::String type) {
@@ -94,6 +94,13 @@ void JMetadataBuilder::setId3v2(TagLib::ID3v2::Tag &tag) {
} }
} }
void JMetadataBuilder::setApe(TagLib::APE::Tag &tag) {
for (auto item : tag.itemListMap()) {
auto key = item.first.upper();
ape.add_custom(key, item.second.values());
}
}
void JMetadataBuilder::setXiph(TagLib::Ogg::XiphComment &tag) { void JMetadataBuilder::setXiph(TagLib::Ogg::XiphComment &tag) {
for (auto field : tag.fieldListMap()) { for (auto field : tag.fieldListMap()) {
auto key = field.first.upper(); auto key = field.first.upper();
@@ -203,15 +210,16 @@ jobject JMetadataBuilder::build() {
JClassRef jMetadataClass { env, "org/oxycblt/musikr/metadata/Metadata" }; JClassRef jMetadataClass { env, "org/oxycblt/musikr/metadata/Metadata" };
jmethodID jMetadataInitMethod = jMetadataClass.method("<init>", jmethodID jMetadataInitMethod = jMetadataClass.method("<init>",
"(Ljava/util/Map;Ljava/util/Map;Ljava/util/Map;[BLorg/" "(Ljava/util/Map;Ljava/util/Map;Ljava/util/Map;Ljava/util/Map;[BLorg/"
"oxycblt/musikr/metadata/Properties;)V"); "oxycblt/musikr/metadata/Properties;)V");
auto jId3v2Map = id3v2.getObject(); auto jId3v2Map = id3v2.getObject();
auto jXiphMap = xiph.getObject(); auto jXiphMap = xiph.getObject();
auto jMp4Map = mp4.getObject(); auto jMp4Map = mp4.getObject();
auto jApeMap = ape.getObject();
if (cover.has_value()) { if (cover.has_value()) {
JByteArrayRef jCoverArray { env, cover.value() }; JByteArrayRef jCoverArray { env, cover.value() };
jobject result = env->NewObject(*jMetadataClass, jMetadataInitMethod, jobject result = env->NewObject(*jMetadataClass, jMetadataInitMethod,
**jId3v2Map, **jXiphMap, **jMp4Map, *jCoverArray, *jProperties); **jId3v2Map, **jXiphMap, **jMp4Map, **jApeMap, *jCoverArray, *jProperties);
return result; return result;
} }
return env->NewObject(*jMetadataClass, jMetadataInitMethod, **jId3v2Map, return env->NewObject(*jMetadataClass, jMetadataInitMethod, **jId3v2Map,
+3
View File
@@ -27,6 +27,7 @@
#include "taglib/id3v2tag.h" #include "taglib/id3v2tag.h"
#include "taglib/xiphcomment.h" #include "taglib/xiphcomment.h"
#include "taglib/mp4tag.h" #include "taglib/mp4tag.h"
#include "taglib/apetag.h"
#include "taglib/audioproperties.h" #include "taglib/audioproperties.h"
#include "JTagMap.h" #include "JTagMap.h"
@@ -40,6 +41,7 @@ public:
void setId3v2(TagLib::ID3v2::Tag &tag); void setId3v2(TagLib::ID3v2::Tag &tag);
void setXiph(TagLib::Ogg::XiphComment &tag); void setXiph(TagLib::Ogg::XiphComment &tag);
void setMp4(TagLib::MP4::Tag &tag); void setMp4(TagLib::MP4::Tag &tag);
void setApe(TagLib::APE::Tag &tag);
void setFlacPictures(TagLib::List<TagLib::FLAC::Picture*> &pics); void setFlacPictures(TagLib::List<TagLib::FLAC::Picture*> &pics);
void setProperties(TagLib::AudioProperties *properties); void setProperties(TagLib::AudioProperties *properties);
@@ -56,6 +58,7 @@ private:
JTagMap id3v2; JTagMap id3v2;
JTagMap xiph; JTagMap xiph;
JTagMap mp4; JTagMap mp4;
JTagMap ape;
}; };
#endif //AUXIO_JMETADATABUILDER_H #endif //AUXIO_JMETADATABUILDER_H
+1 -1
View File
@@ -28,7 +28,7 @@ build_for_arch() {
cmake -B $DST_DIR -DANDROID_NDK_PATH=${NDK_PATH} -DCMAKE_TOOLCHAIN_FILE=${NDK_TOOLCHAIN} \ cmake -B $DST_DIR -DANDROID_NDK_PATH=${NDK_PATH} -DCMAKE_TOOLCHAIN_FILE=${NDK_TOOLCHAIN} \
-DANDROID_ABI=$ARCH -DBUILD_SHARED_LIBS=OFF -DVISIBILITY_HIDDEN=ON -DBUILD_TESTING=OFF \ -DANDROID_ABI=$ARCH -DBUILD_SHARED_LIBS=OFF -DVISIBILITY_HIDDEN=ON -DBUILD_TESTING=OFF \
-DBUILD_EXAMPLES=OFF -DBUILD_BINDINGS=OFF -DWITH_ZLIB=OFF -DCMAKE_BUILD_TYPE=Release \ -DBUILD_EXAMPLES=OFF -DBUILD_BINDINGS=OFF -DWITH_ZLIB=OFF -DCMAKE_BUILD_TYPE=Release \
-DWITH_APE=OFF -DWITH_ASF=OFF -DWITH_ASF=OFF -DWITH_MOD=OFF -DWITH_SHORTEN=OFF \ -DWITH_APE=ON -DWITH_ASF=OFF -DWITH_ASF=OFF -DWITH_MOD=OFF -DWITH_SHORTEN=OFF \
-DWITH_TRUEAUDIO=OFF -DCMAKE_CXX_FLAGS="-fPIC" -DWITH_TRUEAUDIO=OFF -DCMAKE_CXX_FLAGS="-fPIC"
# Try to parallelize the build # Try to parallelize the build
cmake --build $DST_DIR --config Release -j$(nproc) cmake --build $DST_DIR --config Release -j$(nproc)
+8
View File
@@ -51,6 +51,14 @@ bool parseMpeg(const std::string &name, TagLib::MPEG::File *mpegFile,
LOGE("Unable to parse ID3v2 tag in %s: %s", name.c_str(), e.what()); LOGE("Unable to parse ID3v2 tag in %s: %s", name.c_str(), e.what());
} }
} }
auto apeTag = mpegFile->APETag();
if (apeTag != nullptr) {
try {
jBuilder.setApe(*apeTag);
} catch (std::exception &e) {
LOGE("Unable to parse APE tag in %s: %s", name.c_str(), e.what());
}
}
return true; return true;
} }
@@ -19,9 +19,14 @@
package org.oxycblt.musikr package org.oxycblt.musikr
import android.content.Context import android.content.Context
import android.os.SystemClock
import java.util.Collections
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import org.oxycblt.musikr.fs.File
import org.oxycblt.musikr.pipeline.EvaluateStep import org.oxycblt.musikr.pipeline.EvaluateStep
import org.oxycblt.musikr.pipeline.ExploreStep import org.oxycblt.musikr.pipeline.ExploreStep
import org.oxycblt.musikr.pipeline.Explored import org.oxycblt.musikr.pipeline.Explored
@@ -48,7 +53,8 @@ interface Musikr {
* Start loading music using the given config and the configuration provided earlier. * Start loading music using the given config and the configuration provided earlier.
* *
* @param onProgress Optional callback to receive progress on the current status of the music * @param onProgress Optional callback to receive progress on the current status of the music
* pipeline. Warning: These events will be rapid-fire. * pipeline. Intermediate song counts are coalesced, while terminal states are delivered
* promptly.
* @return A handle to the newly created library alongside further cleanup. * @return A handle to the newly created library alongside further cleanup.
*/ */
suspend fun run(onProgress: suspend (IndexingProgress) -> Unit = {}): LibraryResult suspend fun run(onProgress: suspend (IndexingProgress) -> Unit = {}): LibraryResult
@@ -106,6 +112,44 @@ sealed interface IndexingProgress {
data object Indeterminate : IndexingProgress data object Indeterminate : IndexingProgress
} }
/** Coalesces intermediate counts while retaining exact final and terminal progress. */
internal class IndexingProgressCoalescer(
private val intervalMs: Long = 250,
private val clock: () -> Long = SystemClock::elapsedRealtime,
private val onProgress: suspend (IndexingProgress) -> Unit,
) {
private val mutex = Mutex()
private var latestSongs: IndexingProgress.Songs? = null
private var lastEmissionMs: Long? = null
suspend fun submit(progress: IndexingProgress) =
mutex.withLock {
when (progress) {
is IndexingProgress.Songs -> {
latestSongs = progress
val lastEmission = lastEmissionMs
if (lastEmission == null || clock() - lastEmission >= intervalMs) {
flushLatest()
}
}
IndexingProgress.Indeterminate -> {
flushLatest()
onProgress(progress)
lastEmissionMs = clock()
}
}
}
suspend fun flush() = mutex.withLock { flushLatest() }
private suspend fun flushLatest() {
val progress = latestSongs ?: return
onProgress(progress)
latestSongs = null
lastEmissionMs = clock()
}
}
private class MusikrImpl( private class MusikrImpl(
private val config: Config, private val config: Config,
private val exploreStep: ExploreStep, private val exploreStep: ExploreStep,
@@ -113,19 +157,22 @@ private class MusikrImpl(
private val evaluateStep: EvaluateStep, private val evaluateStep: EvaluateStep,
) : Musikr { ) : Musikr {
override suspend fun run(onProgress: suspend (IndexingProgress) -> Unit) = coroutineScope { override suspend fun run(onProgress: suspend (IndexingProgress) -> Unit) = coroutineScope {
val progressCoalescer = IndexingProgressCoalescer(onProgress = onProgress)
onProgress(IndexingProgress.Songs(0, 0)) onProgress(IndexingProgress.Songs(0, 0))
var explored = 0 var explored = 0
var loaded = 0 var loaded = 0
val exploredChannel = Channel<Explored>(Channel.UNLIMITED) val exploredChannel = Channel<Explored>(Channel.UNLIMITED)
val exploredTask = exploreStep.explore(this, exploredChannel) val playlistFiles = Collections.synchronizedList(mutableListOf<File>())
val exploredTask = exploreStep.explore(this, exploredChannel, playlistFiles)
val trackedExploredChannel = Channel<Explored>(Channel.UNLIMITED) val trackedExploredChannel = Channel<Explored>(Channel.UNLIMITED)
val trackedExploredTask = val trackedExploredTask =
tryAsyncWith(trackedExploredChannel, Dispatchers.Main) { tryAsyncWith(trackedExploredChannel, Dispatchers.Main) {
for (item in exploredChannel) { for (item in exploredChannel) {
explored++ explored++
onProgress(IndexingProgress.Songs(loaded, explored)) progressCoalescer.submit(IndexingProgress.Songs(loaded, explored))
trackedExploredChannel.send(item) trackedExploredChannel.send(item)
} }
progressCoalescer.flush()
} }
val extractedChannel = Channel<Extracted>(Channel.UNLIMITED) val extractedChannel = Channel<Extracted>(Channel.UNLIMITED)
val extractedTask = extractStep.extract(this, trackedExploredChannel, extractedChannel) val extractedTask = extractStep.extract(this, trackedExploredChannel, extractedChannel)
@@ -134,12 +181,13 @@ private class MusikrImpl(
tryAsyncWith(trackedExtractedChannel, Dispatchers.Main) { tryAsyncWith(trackedExtractedChannel, Dispatchers.Main) {
for (item in extractedChannel) { for (item in extractedChannel) {
loaded++ loaded++
onProgress(IndexingProgress.Songs(loaded, explored)) progressCoalescer.submit(IndexingProgress.Songs(loaded, explored))
trackedExtractedChannel.send(item) trackedExtractedChannel.send(item)
} }
onProgress(IndexingProgress.Indeterminate) progressCoalescer.flush()
progressCoalescer.submit(IndexingProgress.Indeterminate)
} }
val library = evaluateStep.evaluate(trackedExtractedChannel) val library = evaluateStep.evaluate(trackedExtractedChannel, playlistFiles)
merge(exploredTask, extractedTask, trackedExploredTask, trackedExtractedTask).await() merge(exploredTask, extractedTask, trackedExploredTask, trackedExtractedTask).await()
LibraryResultImpl(config, library) LibraryResultImpl(config, library)
} }
@@ -37,11 +37,14 @@ import org.oxycblt.musikr.tag.parse.ParsedTags
* Create an instance with [from]. * Create an instance with [from].
*/ */
class DBCache private constructor(private val readDao: CacheReadDao) : Cache { class DBCache private constructor(private val readDao: CacheReadDao) : Cache {
private var mapping: Map<Uri, CachedFileData>? = null // The initialized map is immutable, so volatile publication is sufficient for cache hits.
@Volatile private var mapping: Map<Uri, CachedFileData>? = null
private val mappingLock = Mutex() private val mappingLock = Mutex()
override suspend fun read(file: File): CacheResult { override suspend fun read(file: File): CacheResult {
val currentMapping = mappingLock.withLock { val currentMapping =
mapping
?: mappingLock.withLock {
mapping ?: readDao.selectAllSongs().associateBy { it.uri }.also { mapping = it } mapping ?: readDao.selectAllSongs().associateBy { it.uri }.also { mapping = it }
} }
val dbSong = currentMapping[file.uri] ?: return CacheResult.Miss(file) val dbSong = currentMapping[file.uri] ?: return CacheResult.Miss(file)
@@ -50,6 +50,15 @@ private const val PREFIX = "mcf:"
* @param context The [Context] to use to access the filesystem and check for ID validity. * @param context The [Context] to use to access the filesystem and check for ID validity.
*/ */
class FSCovers(private val context: Context) : Covers<FDCover> { class FSCovers(private val context: Context) : Covers<FDCover> {
companion object {
internal fun restore(context: Context, id: String): FDCover? {
if (!id.startsWith(PREFIX)) {
return null
}
return FolderCoverImpl(context, id.substring(PREFIX.length).toUri())
}
}
override suspend fun obtain(id: String): CoverResult<FDCover> { override suspend fun obtain(id: String): CoverResult<FDCover> {
if (!id.startsWith(PREFIX)) { if (!id.startsWith(PREFIX)) {
return CoverResult.Miss() return CoverResult.Miss()
@@ -70,6 +70,8 @@ interface CoverStorage {
suspend fun rm(name: String) suspend fun rm(name: String)
companion object { companion object {
internal fun restore(dir: File, name: String): FDCover = FSStoredCover(File(dir, name))
/** /**
* Create a [CoverStorage] implementation at some directory. Covers will be written in that * Create a [CoverStorage] implementation at some directory. Covers will be written in that
* location. * location.
@@ -40,6 +40,15 @@ private const val PREFIX = "mcs:"
* @param coverStorage The [CoverStorage] to use to obtain the cover data. * @param coverStorage The [CoverStorage] to use to obtain the cover data.
*/ */
class StoredCovers(private val coverStorage: CoverStorage) : Covers<FDCover> { class StoredCovers(private val coverStorage: CoverStorage) : Covers<FDCover> {
companion object {
internal fun restore(id: String, directory: java.io.File): FDCover? {
if (!id.startsWith(PREFIX)) {
return null
}
return StoredCover(CoverStorage.restore(directory, id.substring(PREFIX.length)))
}
}
override suspend fun obtain(id: String): CoverResult<FDCover> { override suspend fun obtain(id: String): CoverResult<FDCover> {
if (!id.startsWith(PREFIX)) { if (!id.startsWith(PREFIX)) {
return CoverResult.Miss() return CoverResult.Miss()
@@ -24,6 +24,9 @@ import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
interface FS { interface FS {
/** The roots playlist entries resolve against, in precedence order. May be empty. */
val locationRoots: List<Path>
suspend fun explore(files: Channel<File>): Deferred<Result<Unit>> suspend fun explore(files: Channel<File>): Deferred<Result<Unit>>
fun track(): Flow<FSUpdate> fun track(): Flow<FSUpdate>
@@ -35,6 +35,7 @@ import org.oxycblt.musikr.fs.FS
import org.oxycblt.musikr.fs.FSUpdate import org.oxycblt.musikr.fs.FSUpdate
import org.oxycblt.musikr.fs.File import org.oxycblt.musikr.fs.File
import org.oxycblt.musikr.fs.Location import org.oxycblt.musikr.fs.Location
import org.oxycblt.musikr.fs.Path
import org.oxycblt.musikr.fs.path.MediaStorePathInterpreter import org.oxycblt.musikr.fs.path.MediaStorePathInterpreter
import org.oxycblt.musikr.fs.path.VolumeManager import org.oxycblt.musikr.fs.path.VolumeManager
import org.oxycblt.musikr.fs.saf.contentResolverSafe import org.oxycblt.musikr.fs.saf.contentResolverSafe
@@ -54,6 +55,15 @@ private constructor(
) : FS { ) : FS {
private val pathInterpreterFactory = MediaStorePathInterpreter.Factory.from(volumeManager) private val pathInterpreterFactory = MediaStorePathInterpreter.Factory.from(volumeManager)
// Include-mode filters are the closest thing MediaStore has to configured locations.
override val locationRoots: List<Path>
get() =
if (query.mode == FilterMode.INCLUDE) {
query.filtered.map { it.path }
} else {
emptyList()
}
@OptIn(ExperimentalCoroutinesApi::class) @OptIn(ExperimentalCoroutinesApi::class)
override suspend fun explore(files: Channel<File>): Deferred<Result<Unit>> = coroutineScope { override suspend fun explore(files: Channel<File>): Deferred<Result<Unit>> = coroutineScope {
tryAsyncWith(files, Dispatchers.IO) { channel -> tryAsyncWith(files, Dispatchers.IO) { channel ->
@@ -0,0 +1,63 @@
/*
* Copyright (c) 2026 Auxio Project
* ValueVolumes.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.musikr.fs.path
import android.content.Context
import org.oxycblt.musikr.fs.Components
import org.oxycblt.musikr.fs.Volume
/** Value-backed internal volume. The display name is not part of its stable identity. */
internal data class InternalVolumeValue(
override val mediaStoreName: String?,
override val components: Components?,
val displayName: String,
) : Volume.Internal {
override fun resolveName(context: Context) = displayName
override fun equals(other: Any?) =
other is InternalVolumeValue &&
mediaStoreName == other.mediaStoreName &&
components == other.components
override fun hashCode() =
31 * (mediaStoreName?.hashCode() ?: 0) + (components?.hashCode() ?: 0)
}
/** Value-backed external volume. The display name is not part of its stable identity. */
internal data class ExternalVolumeValue(
override val id: String?,
override val mediaStoreName: String?,
override val components: Components?,
val displayName: String,
) : Volume.External {
override fun resolveName(context: Context) = displayName
override fun equals(other: Any?) =
other is ExternalVolumeValue &&
id == other.id &&
mediaStoreName == other.mediaStoreName &&
components == other.components
override fun hashCode(): Int {
var result = id?.hashCode() ?: 0
result = 31 * result + (mediaStoreName?.hashCode() ?: 0)
result = 31 * result + (components?.hashCode() ?: 0)
return result
}
}
@@ -42,43 +42,41 @@ internal interface VolumeManager {
companion object { companion object {
fun from(context: Context): VolumeManager = fun from(context: Context): VolumeManager =
VolumeManagerImpl(context.getSystemService(StorageManager::class.java)) VolumeManagerImpl(
context.getSystemService(StorageManager::class.java),
context.applicationContext,
)
} }
} }
private class VolumeManagerImpl(private val storageManager: StorageManager) : VolumeManager { private class VolumeManagerImpl(
private val storageManager: StorageManager,
private val context: Context,
) : VolumeManager {
override fun getInternalVolume(): Volume.Internal = override fun getInternalVolume(): Volume.Internal =
InternalVolumeImpl(storageManager.primaryStorageVolume) storageManager.primaryStorageVolume.toInternalValue(context)
override fun getVolumes() = override fun getVolumes(): List<Volume> =
storageManager.storageVolumesCompat.map { storageManager.storageVolumesCompat.map {
if (it.isInternalCompat) { if (it.isInternalCompat) {
InternalVolumeImpl(it) it.toInternalValue(context)
} else { } else {
ExternalVolumeImpl(it) it.toExternalValue(context)
}
} }
} }
private data class InternalVolumeImpl(val storageVolume: StorageVolume) : Volume.Internal { private fun StorageVolume.toInternalValue(context: Context) =
override val mediaStoreName InternalVolumeValue(
get() = storageVolume.mediaStoreVolumeNameCompat mediaStoreName = mediaStoreVolumeNameCompat,
components = directoryCompat?.let(Components.Companion::parseUnix),
displayName = getDescriptionCompat(context),
)
override val components private fun StorageVolume.toExternalValue(context: Context) =
get() = storageVolume.directoryCompat?.let(Components.Companion::parseUnix) ExternalVolumeValue(
id = uuidCompat,
override fun resolveName(context: Context) = storageVolume.getDescriptionCompat(context) mediaStoreName = mediaStoreVolumeNameCompat,
} components = directoryCompat?.let(Components.Companion::parseUnix),
displayName = getDescriptionCompat(context),
private data class ExternalVolumeImpl(val storageVolume: StorageVolume) : Volume.External { )
override val id
get() = storageVolume.uuidCompat
override val mediaStoreName
get() = storageVolume.mediaStoreVolumeNameCompat
override val components
get() = storageVolume.directoryCompat?.let(Components.Companion::parseUnix)
override fun resolveName(context: Context) = storageVolume.getDescriptionCompat(context)
}
}
@@ -54,6 +54,9 @@ private constructor(
private val contentResolver: ContentResolver, private val contentResolver: ContentResolver,
private val query: Query, private val query: Query,
) : FS { ) : FS {
override val locationRoots: List<Path>
get() = query.source.map { it.path }
override suspend fun explore(files: Channel<File>): Deferred<Result<Unit>> = coroutineScope { override suspend fun explore(files: Channel<File>): Deferred<Result<Unit>> = coroutineScope {
tryAsyncWith(files, Dispatchers.Main) { tryAsyncWith(files, Dispatchers.Main) {
query.source query.source
@@ -22,6 +22,7 @@ data class Metadata(
val id3v2: Map<String, List<String>>, val id3v2: Map<String, List<String>>,
val xiph: Map<String, List<String>>, val xiph: Map<String, List<String>>,
val mp4: Map<String, List<String>>, val mp4: Map<String, List<String>>,
val ape: Map<String, List<String>>,
val cover: ByteArray?, val cover: ByteArray?,
val properties: Properties, val properties: Properties,
) { ) {
@@ -34,6 +35,7 @@ data class Metadata(
if (id3v2 != other.id3v2) return false if (id3v2 != other.id3v2) return false
if (xiph != other.xiph) return false if (xiph != other.xiph) return false
if (mp4 != other.mp4) return false if (mp4 != other.mp4) return false
if (ape != other.ape) return false
if (cover != null) { if (cover != null) {
if (other.cover == null) return false if (other.cover == null) return false
if (!cover.contentEquals(other.cover)) return false if (!cover.contentEquals(other.cover)) return false
@@ -47,6 +49,7 @@ data class Metadata(
var result = id3v2.hashCode() var result = id3v2.hashCode()
result = 31 * result + xiph.hashCode() result = 31 * result + xiph.hashCode()
result = 31 * result + mp4.hashCode() result = 31 * result + mp4.hashCode()
result = 31 * result + ape.hashCode()
result = 31 * result + (cover?.contentHashCode() ?: 0) result = 31 * result + (cover?.contentHashCode() ?: 0)
result = 31 * result + properties.hashCode() result = 31 * result + properties.hashCode()
return result return result
@@ -40,7 +40,7 @@ internal interface SongCore {
* @author Alexander Capehart (OxygenCobalt) * @author Alexander Capehart (OxygenCobalt)
*/ */
internal class SongImpl(private val handle: SongCore) : Song { internal class SongImpl(private val handle: SongCore) : Song {
private val preSong = handle.preSong internal val preSong = handle.preSong
override val uid = preSong.v363Uid override val uid = preSong.v363Uid
@@ -19,24 +19,39 @@
package org.oxycblt.musikr.pipeline package org.oxycblt.musikr.pipeline
import android.content.Context import android.content.Context
import java.util.zip.CRC32
import java.util.zip.CheckedInputStream
import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.Channel
import org.oxycblt.musikr.BuildConfig import org.oxycblt.musikr.BuildConfig
import org.oxycblt.musikr.Config import org.oxycblt.musikr.Config
import org.oxycblt.musikr.Interpretation import org.oxycblt.musikr.Interpretation
import org.oxycblt.musikr.MutableLibrary import org.oxycblt.musikr.MutableLibrary
import org.oxycblt.musikr.fs.FS
import org.oxycblt.musikr.fs.File
import org.oxycblt.musikr.fs.saf.contentResolverSafe
import org.oxycblt.musikr.graph.MusicGraph import org.oxycblt.musikr.graph.MusicGraph
import org.oxycblt.musikr.model.LibraryFactory import org.oxycblt.musikr.model.LibraryFactory
import org.oxycblt.musikr.playlist.PlaylistPathResolver
import org.oxycblt.musikr.playlist.PlaylistReconciler
import org.oxycblt.musikr.playlist.db.StoredPlaylists import org.oxycblt.musikr.playlist.db.StoredPlaylists
import org.oxycblt.musikr.playlist.interpret.PlaylistInterpreter import org.oxycblt.musikr.playlist.interpret.PlaylistInterpreter
import org.oxycblt.musikr.playlist.m3u.M3U
import org.oxycblt.musikr.playlist.m3u.ParsedM3U
import org.oxycblt.musikr.playlist.playlistNameFromFileName
import org.oxycblt.musikr.tag.interpret.PreSong
import org.oxycblt.musikr.tag.interpret.TagInterpreter import org.oxycblt.musikr.tag.interpret.TagInterpreter
internal interface EvaluateStep { internal interface EvaluateStep {
suspend fun evaluate(extractedMusic: Channel<Extracted>): MutableLibrary suspend fun evaluate(
extractedMusic: Channel<Extracted>,
playlistFiles: List<File>,
): MutableLibrary
companion object { companion object {
fun new(context: Context, config: Config, interpretation: Interpretation): EvaluateStep = fun new(context: Context, config: Config, interpretation: Interpretation): EvaluateStep =
EvaluateStepImpl( EvaluateStepImpl(
context, context,
config.fs,
TagInterpreter.new(interpretation), TagInterpreter.new(interpretation),
PlaylistInterpreter.new(interpretation), PlaylistInterpreter.new(interpretation),
config.storage.storedPlaylists, config.storage.storedPlaylists,
@@ -47,21 +62,37 @@ internal interface EvaluateStep {
private class EvaluateStepImpl( private class EvaluateStepImpl(
private val context: Context, private val context: Context,
private val fs: FS,
private val tagInterpreter: TagInterpreter, private val tagInterpreter: TagInterpreter,
private val playlistInterpreter: PlaylistInterpreter, private val playlistInterpreter: PlaylistInterpreter,
private val storedPlaylists: StoredPlaylists, private val storedPlaylists: StoredPlaylists,
private val libraryFactory: LibraryFactory, private val libraryFactory: LibraryFactory,
) : EvaluateStep { ) : EvaluateStep {
override suspend fun evaluate(extractedMusic: Channel<Extracted>): MutableLibrary { override suspend fun evaluate(
extractedMusic: Channel<Extracted>,
playlistFiles: List<File>,
): MutableLibrary {
val builder = MusicGraph.builder() val builder = MusicGraph.builder()
val preSongs = mutableListOf<PreSong>()
for (extracted in extractedMusic) { for (extracted in extractedMusic) {
when (extracted) { when (extracted) {
is RawSong -> builder.add(tagInterpreter.interpret(extracted)) is RawSong -> {
is RawPlaylist -> builder.add(playlistInterpreter.interpret(extracted.file)) val preSong = tagInterpreter.interpret(extracted)
preSongs.add(preSong)
builder.add(preSong)
}
is NotAudio -> {} is NotAudio -> {}
is InvalidSong -> {} is InvalidSong -> {}
} }
} }
if (playlistFiles.isNotEmpty()) {
reconcilePlaylists(playlistFiles, preSongs)
}
// Stored playlists enter the graph after the reconcile pass, so the graph sees the
// settled state.
for (playlistFile in storedPlaylists.read()) {
builder.add(playlistInterpreter.interpret(playlistFile))
}
val graph = builder.build() val graph = builder.build()
// Render graph to Graphviz in debug mode // Render graph to Graphviz in debug mode
@@ -72,4 +103,77 @@ private class EvaluateStepImpl(
return libraryFactory.create(graph, storedPlaylists, playlistInterpreter) return libraryFactory.create(graph, storedPlaylists, playlistInterpreter)
} }
/**
* Reconcile the discovered playlist files against the tracked store. Each file is parsed,
* signed, and resolved in one pass; the reconciler decides keep/replace/create, and the
* actions are applied to the store before stored playlists feed the graph.
*/
private suspend fun reconcilePlaylists(playlistFiles: List<File>, preSongs: List<PreSong>) {
val resolver = PlaylistPathResolver()
val m3u = M3U.new()
val uidsByPath = preSongs.associate { it.path to it.v363Uid }
val roots = fs.locationRoots
val discoveredFiles = mutableListOf<DiscoveredFile>()
for (file in playlistFiles) {
val crc = CRC32()
val parsed =
context.contentResolverSafe.openInputStream(file.uri)?.use { stream ->
m3u.read(CheckedInputStream(stream, crc))
}
?: continue
val paths =
resolver.resolve(parsed.entries, listOf(file.path.directory) + roots) { path ->
path in uidsByPath
}
discoveredFiles.add(DiscoveredFile(file, parsed, crc.value, paths ?: emptyList()))
}
val actions =
PlaylistReconciler.reconcile(
storedPlaylists.readTracked(),
discoveredFiles.map {
PlaylistReconciler.Discovered(
it.file.uri.toString(),
it.signature,
it.songPaths.size,
)
},
)
for (action in actions) {
when (action) {
is PlaylistReconciler.Action.Keep -> {}
is PlaylistReconciler.Action.Replace -> {
val file =
discoveredFiles.first { it.file.uri.toString() == action.file.uri }
storedPlaylists.replaceTracked(
action.tracked.uid,
file.name(),
file.songPaths.mapNotNull { uidsByPath[it] },
action.file.signature,
)
}
is PlaylistReconciler.Action.Create -> {
val file =
discoveredFiles.first { it.file.uri.toString() == action.file.uri }
storedPlaylists.newTracked(
file.name(),
file.songPaths.mapNotNull { uidsByPath[it] },
file.file.uri.toString(),
action.file.signature,
)
}
}
}
}
private data class DiscoveredFile(
val file: File,
val parsed: ParsedM3U,
val signature: Long,
val songPaths: List<org.oxycblt.musikr.fs.Path>,
) {
/** The playlist's name: the file's #PLAYLIST entry, else derived from the file name. */
fun name() =
parsed.name ?: file.path.name?.let { playlistNameFromFileName(it) } ?: "Playlist"
}
} }
@@ -36,7 +36,16 @@ import org.oxycblt.musikr.util.merge
import org.oxycblt.musikr.util.tryAsyncWith import org.oxycblt.musikr.util.tryAsyncWith
internal interface ExploreStep { internal interface ExploreStep {
suspend fun explore(scope: CoroutineScope, explored: Channel<Explored>): Deferred<Result<Unit>> /**
* Explore the file system for music, streaming the results into [explored]. Discovered
* playlist files are buffered into [playlistFiles] for reconciliation once the library is
* fully extracted.
*/
suspend fun explore(
scope: CoroutineScope,
explored: Channel<Explored>,
playlistFiles: MutableList<File>,
): Deferred<Result<Unit>>
companion object { companion object {
fun from(context: Context, config: Config): ExploreStep = fun from(context: Context, config: Config): ExploreStep =
@@ -48,6 +57,7 @@ private class ExploreStepImpl(private val fs: FS, private val storage: Storage)
override suspend fun explore( override suspend fun explore(
scope: CoroutineScope, scope: CoroutineScope,
explored: Channel<Explored>, explored: Channel<Explored>,
playlistFiles: MutableList<File>,
): Deferred<Result<Unit>> { ): Deferred<Result<Unit>> {
val files = Channel<File>(Channel.UNLIMITED) val files = Channel<File>(Channel.UNLIMITED)
val filesTask = fs.explore(files) val filesTask = fs.explore(files)
@@ -62,6 +72,10 @@ private class ExploreStepImpl(private val fs: FS, private val storage: Storage)
file.mimeType != "application/x-ogg" && file.mimeType != "application/x-ogg" &&
file.mimeType != "application/octet-stream") file.mimeType != "application/octet-stream")
) { ) {
if (file.mimeType == M3U.MIME_TYPE) {
// Not audio, but still wanted: buffer for the reconcile pass.
playlistFiles.add(file)
}
return@mapParallel Finalized(NotAudio) return@mapParallel Finalized(NotAudio)
} }
when (val cacheResult = storage.cache.read(file)) { when (val cacheResult = storage.cache.read(file)) {
@@ -100,26 +114,14 @@ private class ExploreStepImpl(private val fs: FS, private val storage: Storage)
} }
} }
} }
val playlists = Channel<Explored>(Channel.UNLIMITED)
val playlistsTask =
scope.tryAsyncWith(playlists, Dispatchers.IO) {
for (playlist in storage.storedPlaylists.read()) {
val rawPlaylist = RawPlaylist(playlist)
it.send(rawPlaylist)
}
}
val mergeTask = val mergeTask =
scope.tryAsyncWith(explored, Dispatchers.Main) { scope.tryAsyncWith(explored, Dispatchers.Main) {
for (item in finalized) { for (item in finalized) {
it.send(item.explored) it.send(item.explored)
} }
for (playlist in playlists) {
it.send(playlist)
}
} }
return scope.merge(filesTask, classifiedTask, exploredTask, playlistsTask, mergeTask) return scope.merge(filesTask, classifiedTask, exploredTask, mergeTask)
} }
private sealed interface Classified private sealed interface Classified
@@ -73,7 +73,6 @@ private class ExtractStepImpl(
scope.mapParallel(PARALLELISM, explored, extract, Dispatchers.IO) { item -> scope.mapParallel(PARALLELISM, explored, extract, Dispatchers.IO) { item ->
when (item) { when (item) {
is RawSong -> Finalized(item) is RawSong -> Finalized(item)
is RawPlaylist -> Finalized(item)
is NewSong -> { is NewSong -> {
when (val result = metadataExtractor.extract(item.file)) { when (val result = metadataExtractor.extract(item.file)) {
is MetadataResult.Success -> is MetadataResult.Success ->
@@ -21,7 +21,6 @@ package org.oxycblt.musikr.pipeline
import org.oxycblt.musikr.covers.Cover import org.oxycblt.musikr.covers.Cover
import org.oxycblt.musikr.fs.File import org.oxycblt.musikr.fs.File
import org.oxycblt.musikr.metadata.Properties import org.oxycblt.musikr.metadata.Properties
import org.oxycblt.musikr.playlist.PlaylistFile
import org.oxycblt.musikr.tag.parse.ParsedTags import org.oxycblt.musikr.tag.parse.ParsedTags
internal sealed interface PipelineItem internal sealed interface PipelineItem
@@ -48,8 +47,6 @@ internal data object InvalidSong : Extracted.Invalid
internal data object NotAudio : Explored.Known, Extracted.Valid internal data object NotAudio : Explored.Known, Extracted.Valid
internal data class RawPlaylist(val file: PlaylistFile) : Explored.Known, Extracted.Valid
internal data class RawSong( internal data class RawSong(
val file: File, val file: File,
val properties: Properties, val properties: Properties,
@@ -20,7 +20,9 @@ package org.oxycblt.musikr.playlist
import android.content.Context import android.content.Context
import android.net.Uri import android.net.Uri
import org.oxycblt.musikr.Library
import org.oxycblt.musikr.Playlist import org.oxycblt.musikr.Playlist
import org.oxycblt.musikr.Song
import org.oxycblt.musikr.fs.Components import org.oxycblt.musikr.fs.Components
import org.oxycblt.musikr.fs.Path import org.oxycblt.musikr.fs.Path
import org.oxycblt.musikr.fs.Volume import org.oxycblt.musikr.fs.Volume
@@ -37,13 +39,16 @@ import org.oxycblt.musikr.playlist.m3u.M3U
*/ */
interface ExternalPlaylistManager { interface ExternalPlaylistManager {
/** /**
* Import the playli L.d("Unable to extract bit rate field") st file at the given [uri]. * Import the playlist file at the given [uri].
* *
* @param uri The [Uri] of the playlist file to import. * @param uri The [Uri] of the playlist file to import.
* @return An [ImportedPlaylist] containing the paths to the files listed in the playlist file, * @param roots Candidate roots to resolve entries against after the playlist file's own
* or null if the playlist could not be imported. * directory, in precedence order. Usually the configured music locations.
* @param library The [Library] to resolve entries against.
* @return An [ImportedPlaylist] containing the resolved songs, or null if the playlist could
* not be imported or no entry resolved.
*/ */
suspend fun import(uri: Uri): ImportedPlaylist? suspend fun import(uri: Uri, roots: List<Path>, library: Library): ImportedPlaylist?
/** /**
* Export the given [playlist] to the given [uri]. * Export the given [playlist] to the given [uri].
@@ -60,7 +65,7 @@ interface ExternalPlaylistManager {
ExternalPlaylistManagerImpl( ExternalPlaylistManagerImpl(
context, context,
DocumentPathFactory.from(context), DocumentPathFactory.from(context),
M3U.from(context), M3U.new(),
) )
} }
} }
@@ -80,40 +85,39 @@ data class ExportConfig(val absolute: Boolean, val windowsPaths: Boolean)
* A playlist that has been imported. * A playlist that has been imported.
* *
* @property name The name of the playlist. May be null if not provided. * @property name The name of the playlist. May be null if not provided.
* @property paths The paths of the files in the playlist. * @property songs The resolved songs of the playlist, in file order. Entries that did not
* resolve are dropped.
* @see ExternalPlaylistManager * @see ExternalPlaylistManager
* @see M3U * @see M3U
*/ */
data class ImportedPlaylist(val name: String?, val paths: List<PossiblePaths>) data class ImportedPlaylist(val name: String?, val songs: List<Song>)
typealias PossiblePaths = List<Path>
private class ExternalPlaylistManagerImpl( private class ExternalPlaylistManagerImpl(
private val context: Context, private val context: Context,
private val documentPathFactory: DocumentPathFactory, private val documentPathFactory: DocumentPathFactory,
private val m3u: M3U, private val m3u: M3U,
) : ExternalPlaylistManager { ) : ExternalPlaylistManager {
override suspend fun import(uri: Uri): ImportedPlaylist? { private val resolver = PlaylistPathResolver()
override suspend fun import(uri: Uri, roots: List<Path>, library: Library): ImportedPlaylist? {
val filePath = val filePath =
documentPathFactory.unpackDocumentUri(uri) documentPathFactory.unpackDocumentUri(uri)
?: Path(Volume.ThirdParty(uri), Components.root()) ?: Path(Volume.ThirdParty(uri), Components.root())
return try { return try {
context.contentResolverSafe.openInputStream(uri)?.use { context.contentResolverSafe.openInputStream(uri)?.use {
val imported = m3u.read(it, filePath.directory) ?: return null val parsed = m3u.read(it) ?: return null
val name = imported.name val paths =
if (name != null) { resolver.resolve(parsed.entries, listOf(filePath.directory) + roots) { path ->
return imported library.findSongByPath(path) != null
} }
// Strip extension ?: return null
val fileName = filePath.name ?: return imported val songs = paths.mapNotNull(library::findSongByPath)
val split = fileName.split(".") val name = parsed.name
var newName = split[0] if (name != null) {
// Replace delimiters with space return ImportedPlaylist(name, songs)
newName = newName.replace(Regex("[_-]"), " ") }
// Replace long stretches of whitespace with one space val fileName = filePath.name ?: return ImportedPlaylist(null, songs)
newName = newName.replace(Regex("\\s+"), " ") return ImportedPlaylist(playlistNameFromFileName(fileName), songs)
return ImportedPlaylist(newName, imported.paths)
} }
} catch (e: Exception) { } catch (e: Exception) {
null null
@@ -43,3 +43,13 @@ internal interface PlaylistHandle {
suspend fun delete() suspend fun delete()
} }
/** Derive a playlist name from a file name: strip the extension, delimiters become spaces. */
internal fun playlistNameFromFileName(fileName: String): String {
// Strip extension
var name = fileName.split(".")[0]
// Replace delimiters with space
name = name.replace(Regex("[_-]"), " ")
// Replace long stretches of whitespace with one space
return name.replace(Regex("\\s+"), " ")
}
@@ -0,0 +1,92 @@
/*
* Copyright (c) 2026 Auxio Project
* PlaylistPathResolver.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.musikr.playlist
import org.oxycblt.musikr.fs.Components
import org.oxycblt.musikr.fs.Path
/**
* Resolves playlist file entries against the indexed library by probe-and-lock: probe entries
* against the candidate roots in order until one resolves, lock that root, then resolve every
* entry against it. All entries in a playlist are assumed to share one root. Absolute entries
* probe with leading components stripped one at a time, which rescues paths written under
* another machine's layout; the locked strip depth then applies to every absolute entry.
*
* Unresolvable entries drop out of the result. A null result means no entry resolved anywhere —
* the only case a playlist fails to resolve.
*
* @author OxygenCobalt (Fork)
*/
internal class PlaylistPathResolver {
/**
* A single playlist entry.
*
* @property components The path as written in the playlist, split into components.
* @property absolute Whether the path was written absolute.
*/
data class Entry(val components: Components, val absolute: Boolean)
/**
* Resolve [entries] against [roots] (in precedence order), using [exists] to test whether a
* resolved path is in the library.
*
* @return The resolved paths in entry order, or null if no entry resolved under any root.
*/
fun resolve(entries: List<Entry>, roots: List<Path>, exists: (Path) -> Boolean): List<Path>? {
var lockedRoot: Path? = null
var lockedStrip = 0
probe@ for (entry in entries) {
// Never strip the file name itself.
val maxStrip = if (entry.absolute) entry.components.components.size - 1 else 0
for (strip in 0..maxStrip) {
for (root in roots) {
val candidate =
Path(root.volume, entry.components.depth(strip).joinedTo(root.components))
if (exists(candidate)) {
lockedRoot = root
lockedStrip = strip
break@probe
}
}
}
}
if (lockedRoot == null) {
return null
}
return entries.mapNotNull { entry ->
val components =
if (entry.absolute) entry.components.depth(lockedStrip) else entry.components
Path(lockedRoot.volume, components.joinedTo(lockedRoot.components)).takeIf(exists)
}
}
/** Join these components onto [base], resolving `.` and `..` segments along the way. */
private fun Components.joinedTo(base: Components): Components {
var result = base
for (component in components) {
result =
when (component) {
".." -> result.parent()
"." -> result
else -> result.child(component)
}
}
return result
}
}
@@ -0,0 +1,86 @@
/*
* Copyright (c) 2026 Auxio Project
* PlaylistReconciler.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.musikr.playlist
import org.oxycblt.musikr.Music
/**
* Reconciles stored tracked playlists against the playlist files discovered in a scan. The file
* on disk wins when it speaks, but never destructively: an unchanged file keeps the stored
* playlist (in-app edits survive), a changed file with at least one resolved entry replaces it
* (in-app edits are discarded), and a file that is missing or resolves nothing keeps the stored
* playlist. Playlists without a source file are unmanaged and never reach this unit.
*
* @author OxygenCobalt (Fork)
*/
internal object PlaylistReconciler {
/**
* A stored playlist's tracking identity.
*
* @property uid The playlist's UID.
* @property sourceUri The document URI of the file the playlist was imported from.
* @property signature The content signature of that file at import time.
*/
data class Tracked(val uid: Music.UID, val sourceUri: String, val signature: Long)
/**
* A playlist file discovered in a scan.
*
* @property uri The document URI of the file.
* @property signature The content signature of the file.
* @property resolvedCount How many entries resolved against the library.
*/
data class Discovered(val uri: String, val signature: Long, val resolvedCount: Int)
/** What to do with a tracked playlist or discovered file after reconciliation. */
sealed interface Action {
/** Nothing changes: keep the stored playlist as-is. */
data class Keep(val tracked: Tracked) : Action
/** The file changed and resolves: re-import it, replacing the stored playlist's songs. */
data class Replace(val tracked: Tracked, val file: Discovered) : Action
/** The file has no stored playlist and resolves: import it as a new tracked playlist. */
data class Create(val file: Discovered) : Action
}
/**
* Reconcile [tracked] stored playlists against [discovered] files, emitting one [Action] per
* input.
*/
fun reconcile(tracked: List<Tracked>, discovered: List<Discovered>): List<Action> {
val filesByUri = discovered.associateBy { it.uri }
val trackedActions =
tracked.map { item ->
val file = filesByUri[item.sourceUri]
when {
file == null -> Action.Keep(item)
file.signature == item.signature -> Action.Keep(item)
file.resolvedCount == 0 -> Action.Keep(item)
else -> Action.Replace(item, file)
}
}
val trackedUris = tracked.mapTo(mutableSetOf()) { it.sourceUri }
val createActions =
discovered
.filter { it.uri !in trackedUris && it.resolvedCount > 0 }
.map { Action.Create(it) }
return trackedActions + createActions
}
}
@@ -43,7 +43,7 @@ import org.oxycblt.musikr.Music
*/ */
@Database( @Database(
entities = [PlaylistInfo::class, PlaylistSong::class, PlaylistSongCrossRef::class], entities = [PlaylistInfo::class, PlaylistSong::class, PlaylistSongCrossRef::class],
version = 75, version = 76,
exportSchema = false, exportSchema = false,
) )
@TypeConverters(Music.UID.TypeConverters::class) @TypeConverters(Music.UID.TypeConverters::class)
@@ -117,7 +117,15 @@ internal abstract class PlaylistDatabase : RoomDatabase() {
washUids(db, "PlaylistInfo", "playlistUid") washUids(db, "PlaylistInfo", "playlistUid")
washUids(db, "PlaylistSongCrossRef", "playlistUid") washUids(db, "PlaylistSongCrossRef", "playlistUid")
} }
},
object : Migration(75, 76) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE PlaylistInfo ADD COLUMN sourceUri TEXT")
db.execSQL(
"ALTER TABLE PlaylistInfo ADD COLUMN sourceSignature INTEGER"
)
} }
},
) )
.fallbackToDestructiveMigration(true) .fallbackToDestructiveMigration(true)
.build() .build()
@@ -143,6 +151,16 @@ internal abstract class PlaylistDao {
@Query("SELECT * FROM PlaylistInfo") @Query("SELECT * FROM PlaylistInfo")
abstract suspend fun readRawPlaylists(): List<RawPlaylist> abstract suspend fun readRawPlaylists(): List<RawPlaylist>
/** Read the [PlaylistInfo] of playlists with a source file, for reconciliation. */
@Query("SELECT * FROM PlaylistInfo WHERE sourceUri IS NOT NULL AND sourceSignature IS NOT NULL")
abstract suspend fun readTrackedInfos(): List<PlaylistInfo>
/** Update the name and source signature of a tracked playlist after a re-import. */
@Query(
"UPDATE PlaylistInfo SET name = :name, sourceSignature = :signature WHERE playlistUid = :playlistUid"
)
abstract suspend fun updateTrackedInfo(playlistUid: Music.UID, name: String, signature: Long)
/** /**
* Create a new playlist. * Create a new playlist.
* *
@@ -46,7 +46,15 @@ internal data class RawPlaylist(
* *
* @author Alexander Capehart (OxygenCobalt) * @author Alexander Capehart (OxygenCobalt)
*/ */
@Entity internal data class PlaylistInfo(@PrimaryKey val playlistUid: Music.UID, val name: String) @Entity
internal data class PlaylistInfo(
@PrimaryKey val playlistUid: Music.UID,
val name: String,
/** The document URI of the file this playlist was imported from. Null if unmanaged. */
val sourceUri: String? = null,
/** The content signature of the source file at import time. Null if unmanaged. */
val sourceSignature: Long? = null,
)
/** /**
* Song information corresponding to a [RawPlaylist] entry. * Song information corresponding to a [RawPlaylist] entry.
@@ -23,11 +23,32 @@ import org.oxycblt.musikr.Music
import org.oxycblt.musikr.Song import org.oxycblt.musikr.Song
import org.oxycblt.musikr.playlist.PlaylistFile import org.oxycblt.musikr.playlist.PlaylistFile
import org.oxycblt.musikr.playlist.PlaylistHandle import org.oxycblt.musikr.playlist.PlaylistHandle
import org.oxycblt.musikr.playlist.PlaylistReconciler
import org.oxycblt.musikr.playlist.SongPointer import org.oxycblt.musikr.playlist.SongPointer
import org.oxycblt.musikr.util.unlikelyToBeNull
abstract class StoredPlaylists { abstract class StoredPlaylists {
internal abstract suspend fun new(name: String, songs: List<Song>): PlaylistHandle internal abstract suspend fun new(name: String, songs: List<Song>): PlaylistHandle
/** Create a playlist tracked against a source file. */
internal abstract suspend fun newTracked(
name: String,
songUids: List<Music.UID>,
sourceUri: String,
sourceSignature: Long,
): PlaylistHandle
/** Replace a tracked playlist with its re-imported file: new name, songs, and signature. */
internal abstract suspend fun replaceTracked(
playlistUid: Music.UID,
name: String,
songUids: List<Music.UID>,
sourceSignature: Long,
)
/** Read the tracking identities of playlists with a source file. */
internal abstract suspend fun readTracked(): List<PlaylistReconciler.Tracked>
internal abstract suspend fun read(): List<PlaylistFile> internal abstract suspend fun read(): List<PlaylistFile>
companion object { companion object {
@@ -43,6 +64,42 @@ private class StoredPlaylistsImpl(private val playlistDao: PlaylistDao) : Stored
return StoredPlaylistHandle(info, playlistDao) return StoredPlaylistHandle(info, playlistDao)
} }
override suspend fun newTracked(
name: String,
songUids: List<Music.UID>,
sourceUri: String,
sourceSignature: Long,
): PlaylistHandle {
val info =
PlaylistInfo(
Music.UID.auxio(Music.UID.Item.PLAYLIST),
name,
sourceUri = sourceUri,
sourceSignature = sourceSignature,
)
playlistDao.insertPlaylist(RawPlaylist(info, songUids.map { PlaylistSong(it) }))
return StoredPlaylistHandle(info, playlistDao)
}
override suspend fun replaceTracked(
playlistUid: Music.UID,
name: String,
songUids: List<Music.UID>,
sourceSignature: Long,
) {
playlistDao.replacePlaylistSongs(playlistUid, songUids.map { PlaylistSong(it) })
playlistDao.updateTrackedInfo(playlistUid, name, sourceSignature)
}
override suspend fun readTracked() =
playlistDao.readTrackedInfos().map {
PlaylistReconciler.Tracked(
it.playlistUid,
unlikelyToBeNull(it.sourceUri),
unlikelyToBeNull(it.sourceSignature),
)
}
override suspend fun read() = override suspend fun read() =
playlistDao.readRawPlaylists().map { playlistDao.readRawPlaylists().map {
PlaylistFile( PlaylistFile(
@@ -18,7 +18,6 @@
package org.oxycblt.musikr.playlist.m3u package org.oxycblt.musikr.playlist.m3u
import android.content.Context
import java.io.BufferedReader import java.io.BufferedReader
import java.io.BufferedWriter import java.io.BufferedWriter
import java.io.InputStream import java.io.InputStream
@@ -27,11 +26,8 @@ import java.io.OutputStream
import org.oxycblt.musikr.Playlist import org.oxycblt.musikr.Playlist
import org.oxycblt.musikr.fs.Components import org.oxycblt.musikr.fs.Components
import org.oxycblt.musikr.fs.Path import org.oxycblt.musikr.fs.Path
import org.oxycblt.musikr.fs.Volume
import org.oxycblt.musikr.fs.path.VolumeManager
import org.oxycblt.musikr.playlist.ExportConfig import org.oxycblt.musikr.playlist.ExportConfig
import org.oxycblt.musikr.playlist.ImportedPlaylist import org.oxycblt.musikr.playlist.PlaylistPathResolver
import org.oxycblt.musikr.playlist.PossiblePaths
import org.oxycblt.musikr.tag.Name import org.oxycblt.musikr.tag.Name
import org.oxycblt.musikr.util.correctWhitespace import org.oxycblt.musikr.util.correctWhitespace
import org.oxycblt.musikr.util.unlikelyToBeNull import org.oxycblt.musikr.util.unlikelyToBeNull
@@ -43,15 +39,13 @@ import org.oxycblt.musikr.util.unlikelyToBeNull
*/ */
abstract class M3U { abstract class M3U {
/** /**
* Reads an M3U file from the given [stream] and returns a [ImportedPlaylist] containing the * Reads an M3U file from the given [stream] and returns the parsed [ParsedM3U]. Entries are
* paths to the files listed in the M3U file. * interpreted but not resolved against the library — see [PlaylistPathResolver].
* *
* @param stream The stream to read the M3U file from. * @param stream The stream to read the M3U file from.
* @param workingDirectory The directory that the M3U file is contained in. This is used to * @return The [ParsedM3U], or null if the file contained no entries.
* resolve relative paths.
* @return An [ImportedPlaylist] containing the paths to the files listed in the M3U file,
*/ */
internal abstract fun read(stream: InputStream, workingDirectory: Path): ImportedPlaylist? internal abstract fun read(stream: InputStream): ParsedM3U?
/** /**
* Writes the given [playlist] to the given [outputStream] in the M3U format,. * Writes the given [playlist] to the given [outputStream] in the M3U format,.
@@ -73,15 +67,22 @@ abstract class M3U {
/** The mime type used for M3U files by the android system. */ /** The mime type used for M3U files by the android system. */
const val MIME_TYPE = "audio/x-mpegurl" const val MIME_TYPE = "audio/x-mpegurl"
internal fun from(context: Context): M3U = M3UImpl(VolumeManager.from(context)) internal fun new(): M3U = M3UImpl()
} }
} }
private class M3UImpl(private val volumeManager: VolumeManager) : M3U() { /**
override fun read(stream: InputStream, workingDirectory: Path): ImportedPlaylist? { * The raw result of parsing an M3U file.
val volumes = volumeManager.getVolumes() *
* @property name The playlist name, if a #PLAYLIST entry was present.
* @property entries The parsed entries in file order.
*/
internal data class ParsedM3U(val name: String?, val entries: List<PlaylistPathResolver.Entry>)
private class M3UImpl : M3U() {
override fun read(stream: InputStream): ParsedM3U? {
val reader = BufferedReader(InputStreamReader(stream)) val reader = BufferedReader(InputStreamReader(stream))
val paths = mutableListOf<PossiblePaths>() val entries = mutableListOf<PlaylistPathResolver.Entry>()
var name: String? = null var name: String? = null
consumeFile@ while (true) { consumeFile@ while (true) {
@@ -112,61 +113,41 @@ private class M3UImpl(private val volumeManager: VolumeManager) : M3U() {
} }
} }
// There is basically no formal specification of file paths in M3U, and it differs // One interpretation per line: resolution against the library happens later, in
// based on the programs that generated it. I more or less have to consider any possible // PlaylistPathResolver.
// interpretation as valid. entries.add(interpretLine(unlikelyToBeNull(path)))
val interpretations = interpretPath(unlikelyToBeNull(path))
val possibilities = interpretations.flatMap {
expandInterpretation(it, workingDirectory, volumes)
} }
paths.add(possibilities) return if (entries.isNotEmpty()) {
} ParsedM3U(name, entries)
return if (paths.isNotEmpty()) {
ImportedPlaylist(name, paths)
} else { } else {
// Couldn't get anything useful out of this file. // Couldn't get anything useful out of this file.
null null
} }
} }
private data class InterpretedPath(val components: Components, val likelyAbsolute: Boolean) /**
* Interpret a line as an entry. There is no formal specification of M3U paths, so the form
private fun interpretPath(path: String): List<InterpretedPath> = * detection is heuristic: unix or windows, absolute or relative. Bare lines parse by
* whichever separator they contain.
*/
private fun interpretLine(path: String): PlaylistPathResolver.Entry =
when { when {
path.startsWith('/') -> listOf(InterpretedPath(Components.parseUnix(path), true)) path.startsWith('/') ->
path.startsWith("./") -> listOf(InterpretedPath(Components.parseUnix(path), false)) PlaylistPathResolver.Entry(Components.parseUnix(path), absolute = true)
path.startsWith("./") ->
PlaylistPathResolver.Entry(Components.parseUnix(path), absolute = false)
path.matches(WINDOWS_VOLUME_PREFIX_REGEX) -> path.matches(WINDOWS_VOLUME_PREFIX_REGEX) ->
listOf(InterpretedPath(Components.parseWindows(path.substring(2)), true)) PlaylistPathResolver.Entry(
path.startsWith("\\") -> listOf(InterpretedPath(Components.parseWindows(path), true)) Components.parseWindows(path.substring(2)), absolute = true
path.startsWith(".\\") -> listOf(InterpretedPath(Components.parseWindows(path), false))
else ->
listOf(
InterpretedPath(Components.parseUnix(path), false),
InterpretedPath(Components.parseWindows(path), true),
) )
} path.startsWith("\\") ->
PlaylistPathResolver.Entry(Components.parseWindows(path), absolute = true)
private fun expandInterpretation( path.startsWith(".\\") ->
path: InterpretedPath, PlaylistPathResolver.Entry(Components.parseWindows(path), absolute = false)
workingDirectory: Path, '\\' in path ->
volumes: List<Volume>, PlaylistPathResolver.Entry(Components.parseWindows(path), absolute = false)
): List<Path> { else -> PlaylistPathResolver.Entry(Components.parseUnix(path), absolute = false)
val absoluteInterpretation = Path(workingDirectory.volume, path.components)
val relativeInterpretation =
Path(workingDirectory.volume, path.components.absoluteTo(workingDirectory.components))
val volumeExactMatch = volumes.find { it.components?.contains(path.components) == true }
val volumeInterpretation = volumeExactMatch?.let {
val components =
unlikelyToBeNull(volumeExactMatch.components).containing(path.components)
Path(volumeExactMatch, components)
}
return if (path.likelyAbsolute) {
listOfNotNull(volumeInterpretation, absoluteInterpretation, relativeInterpretation)
} else {
listOfNotNull(relativeInterpretation, volumeInterpretation, absoluteInterpretation)
}
} }
override fun write( override fun write(
@@ -232,22 +213,6 @@ private class M3UImpl(private val volumeManager: VolumeManager) : M3U() {
newLine() newLine()
} }
private fun Components.absoluteTo(workingDirectory: Components): Components {
var absoluteComponents = workingDirectory
for (component in components) {
when (component) {
// Parent specifier, go "back" one directory (in practice cleave off the last
// component)
".." -> absoluteComponents = absoluteComponents.parent()
// Current directory, the components are already there.
"." -> {}
// New directory, add it
else -> absoluteComponents = absoluteComponents.child(component)
}
}
return absoluteComponents
}
private fun Components.relativeTo(workingDirectory: Components): Components { private fun Components.relativeTo(workingDirectory: Components): Components {
// We want to find the common prefix of the working directory and path, and then // We want to find the common prefix of the working directory and path, and then
// and them combine them with the correct relative elements to make sure they // and them combine them with the correct relative elements to make sure they
@@ -0,0 +1,89 @@
/*
* Copyright (c) 2026 Auxio Project
* LibrarySnapshot.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.musikr.snapshot
import android.content.Context
import java.io.File
import java.io.InputStream
import org.oxycblt.musikr.Config
import org.oxycblt.musikr.Interpretation
import org.oxycblt.musikr.Library
import org.oxycblt.musikr.MutableLibrary
import org.oxycblt.musikr.model.SongImpl
import org.oxycblt.musikr.playlist.db.StoredPlaylists
import org.oxycblt.musikr.playlist.interpret.PlaylistInterpreter
import org.oxycblt.musikr.tag.interpret.PreSong
class LibrarySnapshot
private constructor(
private val context: Context,
private val storedPlaylists: StoredPlaylists,
private val playlistInterpreter: PlaylistInterpreter,
) {
constructor(
context: Context,
config: Config,
) : this(
context,
config.storage.storedPlaylists,
PlaylistInterpreter.new(config.interpretation),
)
constructor(
context: Context,
storedPlaylists: StoredPlaylists,
interpretation: Interpretation,
) : this(context, storedPlaylists, PlaylistInterpreter.new(interpretation))
private val storedCoverDirectory = File(context.filesDir, "covers")
suspend fun capture(
library: Library,
store: LibrarySnapshotStore,
fingerprint: LibrarySnapshotFingerprint,
) {
val songs =
library.songs.map { song ->
(song as? SongImpl)?.preSong
?: throw IllegalArgumentException("Snapshot capture requires Musikr songs")
}
store.replace(
write = { LibrarySnapshotDocument.write(it, songs, fingerprint) },
verify = { read(it, fingerprint) },
)
}
suspend fun restore(
store: LibrarySnapshotStore,
fingerprint: LibrarySnapshotFingerprint,
): MutableLibrary? = store.load { read(it, fingerprint) }
private suspend fun read(
input: InputStream,
fingerprint: LibrarySnapshotFingerprint,
): MutableLibrary =
LibrarySnapshotDocument.read(
input,
fingerprint,
storedCoverDirectory,
context,
storedPlaylists,
playlistInterpreter,
)
}
@@ -0,0 +1,670 @@
/*
* Copyright (c) 2026 Auxio Project
* LibrarySnapshotCodec.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.musikr.snapshot
import android.content.Context
import android.net.Uri
import java.io.DataInputStream
import java.io.DataOutputStream
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.nio.ByteBuffer
import java.nio.charset.CodingErrorAction
import java.text.Collator
import java.util.UUID
import org.oxycblt.musikr.Music
import org.oxycblt.musikr.fs.Components
import org.oxycblt.musikr.fs.Format
import org.oxycblt.musikr.fs.Path
import org.oxycblt.musikr.fs.Volume
import org.oxycblt.musikr.fs.path.ExternalVolumeValue
import org.oxycblt.musikr.fs.path.InternalVolumeValue
import org.oxycblt.musikr.tag.Date
import org.oxycblt.musikr.tag.Disc
import org.oxycblt.musikr.tag.KnownName
import org.oxycblt.musikr.tag.Name
import org.oxycblt.musikr.tag.Placeholder
import org.oxycblt.musikr.tag.ReleaseType
import org.oxycblt.musikr.tag.ReplayGainAdjustment
import org.oxycblt.musikr.tag.Token
import org.oxycblt.musikr.tag.interpret.PreAlbum
import org.oxycblt.musikr.tag.interpret.PreArtist
import org.oxycblt.musikr.tag.interpret.PreArtistsFrom
import org.oxycblt.musikr.tag.interpret.PreGenre
import org.oxycblt.musikr.tag.interpret.PreSong
object LibrarySnapshotCodec {
const val MAGIC = "AUXSNAP"
private const val SCHEMA_VERSION = 1
private const val MAX_STRING_BYTES = 1024 * 1024
private const val MAX_FORMAT_DEPTH = 8
private const val MAX_NAME_TOKENS = 10_000
private const val MAX_SONG_ARTISTS = 10_000
private const val MAX_SONG_GENRES = 10_000
private val MAGIC_BYTES = MAGIC.toByteArray(Charsets.US_ASCII)
data class Header(val magic: String, val schemaVersion: Int)
data class FileProperties(
val uri: Uri,
val path: Path,
val format: Format,
val size: Long,
val modifiedMs: Long,
val addedMs: Long,
)
fun writeHeader(output: OutputStream) {
val dataOutput = DataOutputStream(output)
dataOutput.write(MAGIC_BYTES)
dataOutput.writeInt(SCHEMA_VERSION)
dataOutput.flush()
}
fun readHeader(input: InputStream): Header {
val dataInput = DataInputStream(input)
val magic = ByteArray(MAGIC_BYTES.size)
dataInput.readFully(magic)
if (!magic.contentEquals(MAGIC_BYTES)) {
throw IOException("Invalid snapshot magic")
}
val schemaVersion = dataInput.readInt()
if (schemaVersion != SCHEMA_VERSION) {
throw IOException("Unsupported snapshot schema version: $schemaVersion")
}
return Header(String(magic, Charsets.US_ASCII), schemaVersion)
}
fun writeString(output: OutputStream, value: String) {
val bytes = value.toByteArray(Charsets.UTF_8)
require(bytes.size <= MAX_STRING_BYTES) { "Snapshot string exceeds byte limit" }
val dataOutput = DataOutputStream(output)
dataOutput.writeInt(bytes.size)
dataOutput.write(bytes)
dataOutput.flush()
}
fun readString(input: InputStream): String {
val dataInput = DataInputStream(input)
val byteCount = dataInput.readInt()
if (byteCount < 0 || byteCount > MAX_STRING_BYTES) {
throw IOException("Invalid snapshot string length: $byteCount")
}
val bytes = ByteArray(byteCount)
dataInput.readFully(bytes)
return Charsets.UTF_8.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT)
.decode(ByteBuffer.wrap(bytes))
.toString()
}
fun writeNullableString(output: OutputStream, value: String?) {
val dataOutput = DataOutputStream(output)
dataOutput.writeBoolean(value != null)
if (value != null) {
writeString(dataOutput, value)
}
dataOutput.flush()
}
fun readNullableString(input: InputStream): String? {
val marker = DataInputStream(input).readUnsignedByte()
return when (marker) {
0 -> null
1 -> readString(input)
else -> throw IOException("Invalid nullable string marker: $marker")
}
}
fun writeInt(output: OutputStream, value: Int) {
val dataOutput = DataOutputStream(output)
dataOutput.writeInt(value)
dataOutput.flush()
}
fun readInt(input: InputStream) = DataInputStream(input).readInt()
fun writeLong(output: OutputStream, value: Long) {
val dataOutput = DataOutputStream(output)
dataOutput.writeLong(value)
dataOutput.flush()
}
fun readLong(input: InputStream) = DataInputStream(input).readLong()
fun writeFloat(output: OutputStream, value: Float) {
val dataOutput = DataOutputStream(output)
dataOutput.writeFloat(value)
dataOutput.flush()
}
fun readFloat(input: InputStream) = DataInputStream(input).readFloat()
fun writeBoolean(output: OutputStream, value: Boolean) {
val dataOutput = DataOutputStream(output)
dataOutput.writeBoolean(value)
dataOutput.flush()
}
fun readBoolean(input: InputStream): Boolean {
val marker = DataInputStream(input).readUnsignedByte()
return when (marker) {
0 -> false
1 -> true
else -> throw IOException("Invalid snapshot boolean marker: $marker")
}
}
fun writeNullableFloat(output: OutputStream, value: Float?) {
val dataOutput = DataOutputStream(output)
dataOutput.writeByte(if (value == null) 0 else 1)
if (value != null) {
writeFloat(dataOutput, value)
}
dataOutput.flush()
}
fun readNullableFloat(input: InputStream): Float? {
val marker = DataInputStream(input).readUnsignedByte()
return when (marker) {
0 -> null
1 -> readFloat(input)
else -> throw IOException("Invalid nullable float marker: $marker")
}
}
fun writeCount(output: OutputStream, value: Int, maximum: Int) {
require(maximum >= 0) { "Snapshot collection maximum must be non-negative" }
require(value >= 0 && value <= maximum) { "Snapshot collection count is out of bounds" }
writeInt(output, value)
}
fun readCount(input: InputStream, maximum: Int): Int {
require(maximum >= 0) { "Snapshot collection maximum must be non-negative" }
val value = readInt(input)
if (value < 0 || value > maximum) {
throw IOException("Invalid snapshot collection count: $value")
}
return value
}
fun writeUid(output: OutputStream, value: Music.UID) {
writeString(output, value.toString())
}
fun readUid(input: InputStream): Music.UID {
val encoded = readString(input)
return Music.UID.fromString(encoded) ?: throw IOException("Invalid snapshot UID")
}
fun writeDate(output: OutputStream, value: Date) {
writeString(output, value.toString())
}
fun readDate(input: InputStream): Date {
val encoded = readString(input)
return Date.from(encoded) ?: throw IOException("Invalid snapshot date")
}
fun writeDisc(output: OutputStream, value: Disc) {
writeInt(output, value.number)
writeNullableString(output, value.name)
}
fun readDisc(input: InputStream): Disc {
return Disc(readInt(input), readNullableString(input))
}
fun writeReleaseType(output: OutputStream, value: ReleaseType) {
when (value) {
is ReleaseType.Album -> {
writeInt(output, 0)
writeNullableString(output, value.refinement?.name)
}
is ReleaseType.EP -> {
writeInt(output, 1)
writeNullableString(output, value.refinement?.name)
}
is ReleaseType.Single -> {
writeInt(output, 2)
writeNullableString(output, value.refinement?.name)
}
is ReleaseType.Compilation -> {
writeInt(output, 3)
writeNullableString(output, value.refinement?.name)
}
ReleaseType.Soundtrack -> writeInt(output, 4)
ReleaseType.Mix -> writeInt(output, 5)
ReleaseType.Mixtape -> writeInt(output, 6)
ReleaseType.Demo -> writeInt(output, 7)
}
}
fun readReleaseType(input: InputStream): ReleaseType {
return when (readInt(input)) {
0 -> ReleaseType.Album(readRefinement(input))
1 -> ReleaseType.EP(readRefinement(input))
2 -> ReleaseType.Single(readRefinement(input))
3 -> ReleaseType.Compilation(readRefinement(input))
4 -> ReleaseType.Soundtrack
5 -> ReleaseType.Mix
6 -> ReleaseType.Mixtape
7 -> ReleaseType.Demo
else -> throw IOException("Invalid snapshot release type")
}
}
private fun readRefinement(input: InputStream): ReleaseType.Refinement? {
return when (readNullableString(input)) {
null -> null
"LIVE" -> ReleaseType.Refinement.LIVE
"REMIX" -> ReleaseType.Refinement.REMIX
else -> throw IOException("Invalid snapshot release refinement")
}
}
fun writeReplayGainAdjustment(output: OutputStream, value: ReplayGainAdjustment) {
writeNullableFloat(output, value.track)
writeNullableFloat(output, value.album)
}
fun readReplayGainAdjustment(input: InputStream): ReplayGainAdjustment {
val track = readNullableFloat(input)
val album = readNullableFloat(input)
return ReplayGainAdjustment(track, album)
}
fun writeMusicBrainzId(output: OutputStream, value: UUID?) {
val dataOutput = DataOutputStream(output)
dataOutput.writeByte(if (value == null) 0 else 1)
if (value != null) {
writeLong(dataOutput, value.mostSignificantBits)
writeLong(dataOutput, value.leastSignificantBits)
}
dataOutput.flush()
}
fun readMusicBrainzId(input: InputStream): UUID? {
val marker = DataInputStream(input).readUnsignedByte()
return when (marker) {
0 -> null
1 -> {
val mostSignificantBits = readLong(input)
val leastSignificantBits = readLong(input)
UUID(mostSignificantBits, leastSignificantBits)
}
else -> throw IOException("Invalid snapshot MusicBrainz ID marker: $marker")
}
}
fun writePath(output: OutputStream, value: Path) {
when (val volume = value.volume) {
is InternalVolumeValue -> {
writeInt(output, 0)
writeNullableString(output, volume.mediaStoreName)
writeNullableString(output, volume.components?.unixString)
writeString(output, volume.displayName)
}
is ExternalVolumeValue -> {
writeInt(output, 1)
writeNullableString(output, volume.id)
writeNullableString(output, volume.mediaStoreName)
writeNullableString(output, volume.components?.unixString)
writeString(output, volume.displayName)
}
else -> throw IOException("Unsupported snapshot path volume")
}
writeString(output, value.components.unixString)
}
fun readPath(input: InputStream): Path {
val volume: Volume =
when (readInt(input)) {
0 -> {
val mediaStoreName = readNullableString(input)
val components = readNullableComponents(input)
InternalVolumeValue(mediaStoreName, components, readString(input))
}
1 -> {
val id = readNullableString(input)
val mediaStoreName = readNullableString(input)
val components = readNullableComponents(input)
ExternalVolumeValue(id, mediaStoreName, components, readString(input))
}
else -> throw IOException("Invalid snapshot path volume")
}
return Path(volume, Components.parseUnix(readString(input)))
}
private fun readNullableComponents(input: InputStream): Components? {
return readNullableString(input)?.let { Components.parseUnix(it) }
}
fun writeUri(output: OutputStream, value: Uri) {
writeString(output, value.toString())
}
fun readUri(input: InputStream): Uri {
return Uri.parse(readString(input))
}
fun writeFormat(output: OutputStream, value: Format) {
writeFormat(output, value, depth = 0)
}
private fun writeFormat(output: OutputStream, value: Format, depth: Int) {
require(depth <= MAX_FORMAT_DEPTH) { "Snapshot format nesting exceeds depth limit" }
when (value) {
Format.MPEG3 -> writeInt(output, 0)
is Format.MPEG4 -> {
writeInt(output, 1)
writeNullableFormat(output, value.containing, depth + 1)
}
Format.AAC -> writeInt(output, 2)
Format.ALAC -> writeInt(output, 3)
is Format.Ogg -> {
writeInt(output, 4)
writeNullableFormat(output, value.containing, depth + 1)
}
Format.Opus -> writeInt(output, 5)
Format.Vorbis -> writeInt(output, 6)
Format.FLAC -> writeInt(output, 7)
Format.Wav -> writeInt(output, 8)
is Format.Unknown -> {
writeInt(output, 9)
writeString(output, value.mimeType)
}
}
}
private fun writeNullableFormat(output: OutputStream, value: Format?, depth: Int) {
writeBoolean(output, value != null)
if (value != null) {
writeFormat(output, value, depth)
}
}
fun readFormat(input: InputStream): Format {
return readFormat(input, depth = 0)
}
private fun readFormat(input: InputStream, depth: Int): Format {
if (depth > MAX_FORMAT_DEPTH) {
throw IOException("Snapshot format nesting exceeds depth limit")
}
return when (readInt(input)) {
0 -> Format.MPEG3
1 -> Format.MPEG4(readNullableFormat(input, depth + 1))
2 -> Format.AAC
3 -> Format.ALAC
4 -> Format.Ogg(readNullableFormat(input, depth + 1))
5 -> Format.Opus
6 -> Format.Vorbis
7 -> Format.FLAC
8 -> Format.Wav
9 -> Format.Unknown(readString(input))
else -> throw IOException("Invalid snapshot audio format")
}
}
private fun readNullableFormat(input: InputStream, depth: Int): Format? {
return if (readBoolean(input)) readFormat(input, depth) else null
}
fun writeFileProperties(output: OutputStream, value: FileProperties) {
writeUri(output, value.uri)
writePath(output, value.path)
writeFormat(output, value.format)
writeLong(output, value.size)
writeLong(output, value.modifiedMs)
writeLong(output, value.addedMs)
}
fun readFileProperties(input: InputStream): FileProperties {
val uri = readUri(input)
val path = readPath(input)
val format = readFormat(input)
val size = readLong(input)
val modifiedMs = readLong(input)
val addedMs = readLong(input)
return FileProperties(uri, path, format, size, modifiedMs, addedMs)
}
fun writeName(output: OutputStream, value: Name) {
when (value) {
is Name.Unknown -> {
writeInt(output, 0)
writeInt(
output,
when (value.placeholder) {
Placeholder.ALBUM -> 0
Placeholder.ARTIST -> 1
Placeholder.GENRE -> 2
},
)
}
is Name.Known -> {
writeInt(output, 1)
writeString(output, value.raw)
writeNullableString(output, value.sort)
writeCount(output, value.tokens.size, MAX_NAME_TOKENS)
for (token in value.tokens) {
writeString(output, token.value)
writeInt(
output,
when (token.type) {
Token.Type.NUMERIC -> 0
Token.Type.LEXICOGRAPHIC -> 1
},
)
}
}
}
}
fun readName(input: InputStream): Name {
return when (readInt(input)) {
0 -> Name.Unknown(readPlaceholder(input))
1 -> readKnownName(input)
else -> throw IOException("Invalid snapshot name")
}
}
private fun readPlaceholder(input: InputStream): Placeholder {
return when (readInt(input)) {
0 -> Placeholder.ALBUM
1 -> Placeholder.ARTIST
2 -> Placeholder.GENRE
else -> throw IOException("Invalid snapshot name placeholder")
}
}
private fun readKnownName(input: InputStream): KnownName {
val raw = readString(input)
val sort = readNullableString(input)
val count = readCount(input, MAX_NAME_TOKENS)
val collator = Collator.getInstance().apply { strength = Collator.PRIMARY }
val tokens =
List(count) {
val value = readString(input)
val type =
when (readInt(input)) {
0 -> Token.Type.NUMERIC
1 -> Token.Type.LEXICOGRAPHIC
else -> throw IOException("Invalid snapshot token type")
}
Token(collator.getCollationKey(value), type)
}
return KnownName(raw, sort, tokens)
}
internal fun writePreSong(output: OutputStream, value: PreSong) {
writeUid(output, value.v363Uid)
writeUid(output, value.v400Uid)
writeUid(output, value.v401Uid)
writeMusicBrainzId(output, value.musicBrainzId)
writeName(output, value.name)
writeString(output, value.rawName)
writeNullableInt(output, value.track)
writeBoolean(output, value.disc != null)
value.disc?.let { writeDisc(output, it) }
writeBoolean(output, value.date != null)
value.date?.let { writeDate(output, it) }
writeFileProperties(
output,
FileProperties(
value.uri,
value.path,
value.format,
value.size,
value.modifiedMs,
value.addedMs,
),
)
writeLong(output, value.durationMs)
writeInt(output, value.bitrateKbps)
writeInt(output, value.sampleRateHz)
writeReplayGainAdjustment(output, value.replayGainAdjustment)
writeNullableString(output, value.cover?.id)
writePreAlbum(output, value.preAlbum)
writePreArtists(output, value.preArtists)
writeCount(output, value.preGenres.size, MAX_SONG_GENRES)
value.preGenres.forEach { writePreGenre(output, it) }
}
internal fun readPreSong(
input: InputStream,
storedCoverDirectory: File,
context: Context,
): PreSong {
val v363Uid = readUid(input)
val v400Uid = readUid(input)
val v401Uid = readUid(input)
val musicBrainzId = readMusicBrainzId(input)
val name = readName(input) as? Name.Known ?: throw IOException("Invalid snapshot song name")
val rawName = readString(input)
val track = readNullableInt(input)
val disc = if (readBoolean(input)) readDisc(input) else null
val date = if (readBoolean(input)) readDate(input) else null
val fileProperties = readFileProperties(input)
val durationMs = readLong(input)
val bitrateKbps = readInt(input)
val sampleRateHz = readInt(input)
val replayGainAdjustment = readReplayGainAdjustment(input)
val coverId = readNullableString(input)
val cover = LibrarySnapshotCovers.restore(coverId, storedCoverDirectory, context)
val preAlbum = readPreAlbum(input)
val preArtists = readPreArtists(input)
val preGenres = List(readCount(input, MAX_SONG_GENRES)) { readPreGenre(input) }
return PreSong(
v363Uid = v363Uid,
v400Uid = v400Uid,
v401Uid = v401Uid,
musicBrainzId = musicBrainzId,
name = name,
rawName = rawName,
track = track,
disc = disc,
date = date,
uri = fileProperties.uri,
path = fileProperties.path,
format = fileProperties.format,
size = fileProperties.size,
durationMs = durationMs,
bitrateKbps = bitrateKbps,
sampleRateHz = sampleRateHz,
replayGainAdjustment = replayGainAdjustment,
modifiedMs = fileProperties.modifiedMs,
addedMs = fileProperties.addedMs,
cover = cover,
preAlbum = preAlbum,
preArtists = preArtists,
preGenres = preGenres,
)
}
private fun writeNullableInt(output: OutputStream, value: Int?) {
writeBoolean(output, value != null)
value?.let { writeInt(output, it) }
}
private fun readNullableInt(input: InputStream): Int? {
return if (readBoolean(input)) readInt(input) else null
}
private fun writePreAlbum(output: OutputStream, value: PreAlbum) {
writeMusicBrainzId(output, value.musicBrainzId)
writeName(output, value.name)
writeNullableString(output, value.rawName)
writeReleaseType(output, value.releaseType)
when (val artists = value.preArtists) {
is PreArtistsFrom.Individual -> {
writeInt(output, 0)
writePreArtists(output, artists.preArtists)
}
is PreArtistsFrom.Album -> {
writeInt(output, 1)
writePreArtists(output, artists.preArtists)
}
}
}
private fun readPreAlbum(input: InputStream): PreAlbum {
val musicBrainzId = readMusicBrainzId(input)
val name = readName(input)
val rawName = readNullableString(input)
val releaseType = readReleaseType(input)
val artistsTag = readInt(input)
val preArtists = readPreArtists(input)
val artists =
when (artistsTag) {
0 -> PreArtistsFrom.Individual(preArtists)
1 -> PreArtistsFrom.Album(preArtists)
else -> throw IOException("Invalid snapshot album artist source")
}
return PreAlbum(musicBrainzId, name, rawName, releaseType, artists)
}
private fun writePreArtists(output: OutputStream, value: List<PreArtist>) {
writeCount(output, value.size, MAX_SONG_ARTISTS)
for (artist in value) {
writeMusicBrainzId(output, artist.musicBrainzId)
writeName(output, artist.name)
writeNullableString(output, artist.rawName)
}
}
private fun readPreArtists(input: InputStream): List<PreArtist> {
return List(readCount(input, MAX_SONG_ARTISTS)) {
PreArtist(readMusicBrainzId(input), readName(input), readNullableString(input))
}
}
private fun writePreGenre(output: OutputStream, value: PreGenre) {
writeName(output, value.name)
writeNullableString(output, value.rawName)
}
private fun readPreGenre(input: InputStream): PreGenre {
return PreGenre(readName(input), readNullableString(input))
}
}
@@ -0,0 +1,32 @@
/*
* Copyright (c) 2026 Auxio Project
* LibrarySnapshotCovers.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.musikr.snapshot
import android.content.Context
import java.io.File
import org.oxycblt.musikr.covers.FDCover
import org.oxycblt.musikr.covers.fs.FSCovers
import org.oxycblt.musikr.covers.stored.StoredCovers
object LibrarySnapshotCovers {
fun restore(id: String?, storedCoverDirectory: File, context: Context): FDCover? =
id?.let {
StoredCovers.restore(it, storedCoverDirectory) ?: FSCovers.restore(context, it)
}
}
@@ -0,0 +1,82 @@
/*
* Copyright (c) 2026 Auxio Project
* LibrarySnapshotDocument.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.musikr.snapshot
import android.content.Context
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.util.zip.CRC32
import java.util.zip.CheckedInputStream
import java.util.zip.CheckedOutputStream
import org.oxycblt.musikr.MutableLibrary
import org.oxycblt.musikr.playlist.db.StoredPlaylists
import org.oxycblt.musikr.playlist.interpret.PlaylistInterpreter
import org.oxycblt.musikr.tag.interpret.PreSong
internal object LibrarySnapshotDocument {
private const val MAX_SONGS = 100_000
fun write(
output: OutputStream,
songs: List<PreSong>,
fingerprint: LibrarySnapshotFingerprint,
) {
LibrarySnapshotCodec.writeHeader(output)
val checkedOutput = CheckedOutputStream(output, CRC32())
LibrarySnapshotFingerprintCodec.write(checkedOutput, fingerprint)
LibrarySnapshotCodec.writeCount(checkedOutput, songs.size, MAX_SONGS)
for (song in songs) {
LibrarySnapshotCodec.writePreSong(checkedOutput, song)
}
LibrarySnapshotCodec.writeLong(output, checkedOutput.checksum.value)
}
suspend fun read(
input: InputStream,
expectedFingerprint: LibrarySnapshotFingerprint,
storedCoverDirectory: File,
context: Context,
storedPlaylists: StoredPlaylists,
playlistInterpreter: PlaylistInterpreter,
): MutableLibrary {
LibrarySnapshotCodec.readHeader(input)
val checkedInput = CheckedInputStream(input, CRC32())
val fingerprint = LibrarySnapshotFingerprintCodec.read(checkedInput)
if (fingerprint != expectedFingerprint) {
throw IOException("Snapshot fingerprint mismatch")
}
val songCount = LibrarySnapshotCodec.readCount(checkedInput, MAX_SONGS)
val songs = ArrayList<PreSong>(songCount)
repeat(songCount) {
songs.add(
LibrarySnapshotCodec.readPreSong(checkedInput, storedCoverDirectory, context)
)
}
val expectedChecksum = LibrarySnapshotCodec.readLong(input)
if (checkedInput.checksum.value != expectedChecksum) {
throw IOException("Snapshot checksum mismatch")
}
if (input.read() != -1) {
throw IOException("Trailing snapshot data")
}
return LibrarySnapshotGraph.restore(songs, storedPlaylists, playlistInterpreter)
}
}
@@ -0,0 +1,80 @@
/*
* Copyright (c) 2026 Auxio Project
* LibrarySnapshotFingerprint.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.musikr.snapshot
import java.io.InputStream
import java.io.OutputStream
data class LibrarySnapshotFingerprint(
val sourceMode: String,
val sourceRoots: List<String>,
val excludedRoots: List<String>,
val withHidden: Boolean,
val excludeNonMusic: Boolean,
val intelligentSorting: Boolean,
val separators: String,
val coverMode: String,
)
internal object LibrarySnapshotFingerprintCodec {
private const val MAX_ROOT_IDENTITIES = 1_000
fun write(output: OutputStream, value: LibrarySnapshotFingerprint) {
LibrarySnapshotCodec.writeString(output, value.sourceMode)
writeStrings(output, value.sourceRoots)
writeStrings(output, value.excludedRoots)
LibrarySnapshotCodec.writeBoolean(output, value.withHidden)
LibrarySnapshotCodec.writeBoolean(output, value.excludeNonMusic)
LibrarySnapshotCodec.writeBoolean(output, value.intelligentSorting)
LibrarySnapshotCodec.writeString(output, value.separators)
LibrarySnapshotCodec.writeString(output, value.coverMode)
}
fun read(input: InputStream): LibrarySnapshotFingerprint {
val sourceMode = LibrarySnapshotCodec.readString(input)
val sourceRoots = readStrings(input)
val excludedRoots = readStrings(input)
val withHidden = LibrarySnapshotCodec.readBoolean(input)
val excludeNonMusic = LibrarySnapshotCodec.readBoolean(input)
val intelligentSorting = LibrarySnapshotCodec.readBoolean(input)
val separators = LibrarySnapshotCodec.readString(input)
val coverMode = LibrarySnapshotCodec.readString(input)
return LibrarySnapshotFingerprint(
sourceMode,
sourceRoots,
excludedRoots,
withHidden,
excludeNonMusic,
intelligentSorting,
separators,
coverMode,
)
}
private fun writeStrings(output: OutputStream, values: List<String>) {
LibrarySnapshotCodec.writeCount(output, values.size, MAX_ROOT_IDENTITIES)
values.forEach { LibrarySnapshotCodec.writeString(output, it) }
}
private fun readStrings(input: InputStream): List<String> {
return List(LibrarySnapshotCodec.readCount(input, MAX_ROOT_IDENTITIES)) {
LibrarySnapshotCodec.readString(input)
}
}
}
@@ -0,0 +1,42 @@
/*
* Copyright (c) 2026 Auxio Project
* LibrarySnapshotGraph.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.musikr.snapshot
import org.oxycblt.musikr.MutableLibrary
import org.oxycblt.musikr.graph.MusicGraph
import org.oxycblt.musikr.model.LibraryFactory
import org.oxycblt.musikr.playlist.db.StoredPlaylists
import org.oxycblt.musikr.playlist.interpret.PlaylistInterpreter
import org.oxycblt.musikr.tag.interpret.PreSong
internal object LibrarySnapshotGraph {
suspend fun restore(
songs: List<PreSong>,
storedPlaylists: StoredPlaylists,
playlistInterpreter: PlaylistInterpreter,
): MutableLibrary {
val builder = MusicGraph.builder()
songs.forEach { builder.add(it) }
for (file in storedPlaylists.read()) {
builder.add(playlistInterpreter.interpret(file))
}
return LibraryFactory.new()
.create(builder.build(), storedPlaylists, playlistInterpreter)
}
}
@@ -0,0 +1,83 @@
/*
* Copyright (c) 2026 Auxio Project
* LibrarySnapshotStore.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.musikr.snapshot
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardCopyOption
import kotlin.coroutines.cancellation.CancellationException
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
class LibrarySnapshotStore
internal constructor(
private val directory: File,
private val atomicMove: (Path, Path) -> Unit,
) {
constructor(
directory: File
) : this(
directory,
{ source, target ->
Files.move(
source,
target,
StandardCopyOption.ATOMIC_MOVE,
StandardCopyOption.REPLACE_EXISTING,
)
},
)
private val snapshot = File(directory, "library.snapshot")
suspend fun <T> load(read: suspend (InputStream) -> T): T? {
if (!snapshot.isFile) {
return null
}
return try {
snapshot.inputStream().use { read(it) }
} catch (exception: CancellationException) {
throw exception
} catch (exception: Exception) {
null
}
}
suspend fun replace(
write: suspend (OutputStream) -> Unit,
verify: suspend (InputStream) -> Unit,
) {
if (!directory.isDirectory && !directory.mkdirs() && !directory.isDirectory) {
throw IOException("Unable to create library snapshot directory")
}
val tempFile = File.createTempFile("${snapshot.name}.", ".tmp", directory)
try {
tempFile.outputStream().use { write(it) }
tempFile.inputStream().use { verify(it) }
currentCoroutineContext().ensureActive()
atomicMove(tempFile.toPath(), snapshot.toPath())
} finally {
tempFile.delete()
}
}
}
@@ -70,6 +70,13 @@ sealed interface Name : Comparable<Name> {
} }
} }
/** Shared value implementation used by live naming and snapshot restoration. */
internal data class KnownName(
override val raw: String,
override val sort: String?,
override val tokens: List<Token>,
) : Name.Known()
/** An individual part of a name string that can be compared intelligently. */ /** An individual part of a name string that can be compared intelligently. */
class Token internal constructor(internal val collationKey: CollationKey, internal val type: Type) : class Token internal constructor(internal val collationKey: CollationKey, internal val type: Type) :
Comparable<Token> { Comparable<Token> {
@@ -22,6 +22,8 @@ import android.icu.text.Transliterator
import android.os.Build import android.os.Build
import java.text.CollationKey import java.text.CollationKey
import java.text.Collator import java.text.Collator
import java.util.concurrent.ConcurrentHashMap
import org.oxycblt.musikr.tag.KnownName
import org.oxycblt.musikr.tag.Name import org.oxycblt.musikr.tag.Name
import org.oxycblt.musikr.tag.Placeholder import org.oxycblt.musikr.tag.Placeholder
import org.oxycblt.musikr.tag.Token import org.oxycblt.musikr.tag.Token
@@ -37,53 +39,67 @@ abstract class Naming {
abstract fun name(raw: String, sort: String?): Name.Known abstract fun name(raw: String, sort: String?): Name.Known
companion object { companion object {
fun intelligent(): Naming = IntelligentNaming fun intelligent(): Naming = IntelligentNaming()
fun simple(): Naming = SimpleNaming fun simple(): Naming = SimpleNaming
} }
} }
data object IntelligentNaming : Naming() { class IntelligentNaming(
override fun name(raw: String, sort: String?): Name.Known = IntelligentKnownName(raw, sort) transliteratorFactory: () -> (String) -> String = ::newTransliterator
) : Naming() {
private val tokenCache = ConcurrentHashMap<String, List<Token>>()
private val transliterators =
object : ThreadLocal<(String) -> String>() {
override fun initialValue(): (String) -> String = transliteratorFactory()
}
override fun name(raw: String, sort: String?): Name.Known {
val effectiveName = sort ?: raw
return KnownName(
raw,
sort,
tokenCache.computeIfAbsent(effectiveName) {
parseTokens(it, requireNotNull(transliterators.get()))
},
)
}
} }
data object SimpleNaming : Naming() { data object SimpleNaming : Naming() {
override fun name(raw: String, sort: String?): Name.Known = SimpleKnownName(raw, sort) override fun name(raw: String, sort: String?): Name.Known =
KnownName(raw, sort, simpleTokens(raw, sort))
} }
private val collator: Collator = Collator.getInstance().apply { strength = Collator.PRIMARY } private val collator: Collator = Collator.getInstance().apply { strength = Collator.PRIMARY }
private val punctRegex by lazy { Regex("[\\p{Punct}+]") } private val punctRegex by lazy { Regex("[\\p{Punct}+]") }
private val anyLatinAvailable by lazy {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q &&
Transliterator.getAvailableIDs().toList().contains("Any-Latin")
}
private fun newTransliterator(): (String) -> String {
if (!anyLatinAvailable) return { name -> name }
val transliterator = Transliterator.getInstance("Any-Latin;")
return { name: String -> transliterator.transliterate(name) }
}
// TODO: Consider how you want to handle whitespace and "gaps" in names. // TODO: Consider how you want to handle whitespace and "gaps" in names.
/**
* Plain [Name.Known] implementation that is internationalization-safe.
*
* @author Alexander Capehart (OxygenCobalt)
*/
private data class SimpleKnownName(override val raw: String, override val sort: String?) :
Name.Known() {
override val tokens = listOf(parseToken(sort ?: raw))
private fun parseToken(name: String): Token { private fun parseToken(name: String): Token {
// Remove excess punctuation from the string, as those usually aren't considered in sorting. // Remove excess punctuation from the string, as those usually aren't considered in sorting.
val stripped = name.replace(punctRegex, "").trim().ifEmpty { name } val stripped = name.replace(punctRegex, "").trim().ifEmpty { name }
val collationKey = collator.getCollationKey(stripped) val collationKey = collator.getCollationKey(stripped)
// Always use lexicographic mode since we aren't parsing any numeric components // Always use lexicographic mode since we aren't parsing any numeric components.
return Token(collationKey, Token.Type.LEXICOGRAPHIC) return Token(collationKey, Token.Type.LEXICOGRAPHIC)
} }
}
/** private fun simpleTokens(raw: String, sort: String?) = listOf(parseToken(sort ?: raw))
* [Name.Known] implementation that adds advanced sorting behavior at the cost of localization.
*
* @author Alexander Capehart (OxygenCobalt)
*/
private data class IntelligentKnownName(override val raw: String, override val sort: String?) :
Name.Known() {
override val tokens = parseTokens(sort ?: raw)
private fun parseTokens(name: String): List<Token> {
private val TOKEN_REGEX by lazy { Regex("(\\d+)|(\\D+)") }
private fun parseTokens(name: String, transliterate: (String) -> String): List<Token> {
// TODO: This routine is consuming much of the song building runtime, find a way to // TODO: This routine is consuming much of the song building runtime, find a way to
// optimize it // optimize it
var stripped = var stripped =
@@ -104,12 +120,7 @@ private data class IntelligentKnownName(override val raw: String, override val s
} }
// Transliterate to latin if available // Transliterate to latin if available
if ( stripped = transliterate(stripped)
Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q &&
Transliterator.getAvailableIDs().toList().contains("Any-Latin")
) {
stripped = Transliterator.getInstance("Any-Latin;").transliterate(stripped)
}
// To properly compare numeric components in names, we have to split them up into // To properly compare numeric components in names, we have to split them up into
// individual lexicographic and numeric tokens and then individually compare them // individual lexicographic and numeric tokens and then individually compare them
@@ -122,8 +133,7 @@ private data class IntelligentKnownName(override val raw: String, override val s
// Separate each token into their numeric and lexicographic counterparts. // Separate each token into their numeric and lexicographic counterparts.
if (token.first().isDigit()) { if (token.first().isDigit()) {
// The digit string comparison breaks with preceding zero digits, remove those // The digit string comparison breaks with preceding zero digits, remove those
val digits = val digits = token.trimStart { Character.getNumericValue(it) == 0 }.ifEmpty { token }
token.trimStart { Character.getNumericValue(it) == 0 }.ifEmpty { token }
// Other languages have other types of digit strings, still use collation keys // Other languages have other types of digit strings, still use collation keys
collationKey = collator.getCollationKey(digits) collationKey = collator.getCollationKey(digits)
type = Token.Type.NUMERIC type = Token.Type.NUMERIC
@@ -134,8 +144,3 @@ private data class IntelligentKnownName(override val raw: String, override val s
Token(collationKey, type) Token(collationKey, type)
} }
} }
companion object {
private val TOKEN_REGEX by lazy { Regex("(\\d+)|(\\D+)") }
}
}
@@ -253,15 +253,18 @@ internal fun Metadata.isCompilation() =
?: id3v2["TXXX:COMPILATION"] ?: id3v2["TXXX:COMPILATION"]
?: id3v2["TXXX:ITUNESCOMPILATION"]) == listOf("1") ?: id3v2["TXXX:ITUNESCOMPILATION"]) == listOf("1")
// ReplayGain information // ReplayGain information. APE is preferred over the other tag formats: it is the only ReplayGain
// carrier in some libraries, and where it coexists with ID3v2 it is the more deliberate choice.
internal fun Metadata.replayGainTrackAdjustment() = internal fun Metadata.replayGainTrackAdjustment() =
(xiph["R128_TRACK_GAIN"]?.parseR128Adjustment() (ape["REPLAYGAIN_TRACK_GAIN"]?.parseReplayGainAdjustment()
?: xiph["R128_TRACK_GAIN"]?.parseR128Adjustment()
?: xiph["REPLAYGAIN_TRACK_GAIN"]?.parseReplayGainAdjustment() ?: xiph["REPLAYGAIN_TRACK_GAIN"]?.parseReplayGainAdjustment()
?: mp4["----:COM.APPLE.ITUNES:REPLAYGAIN_TRACK_GAIN"]?.parseReplayGainAdjustment() ?: mp4["----:COM.APPLE.ITUNES:REPLAYGAIN_TRACK_GAIN"]?.parseReplayGainAdjustment()
?: id3v2["TXXX:REPLAYGAIN_TRACK_GAIN"]?.parseReplayGainAdjustment()) ?: id3v2["TXXX:REPLAYGAIN_TRACK_GAIN"]?.parseReplayGainAdjustment())
internal fun Metadata.replayGainAlbumAdjustment() = internal fun Metadata.replayGainAlbumAdjustment() =
(xiph["R128_ALBUM_GAIN"]?.parseR128Adjustment() (ape["REPLAYGAIN_ALBUM_GAIN"]?.parseReplayGainAdjustment()
?: xiph["R128_ALBUM_GAIN"]?.parseR128Adjustment()
?: xiph["REPLAYGAIN_ALBUM_GAIN"]?.parseReplayGainAdjustment() ?: xiph["REPLAYGAIN_ALBUM_GAIN"]?.parseReplayGainAdjustment()
?: mp4["----:COM.APPLE.ITUNES:REPLAYGAIN_ALBUM_GAIN"]?.parseReplayGainAdjustment() ?: mp4["----:COM.APPLE.ITUNES:REPLAYGAIN_ALBUM_GAIN"]?.parseReplayGainAdjustment()
?: id3v2["TXXX:REPLAYGAIN_ALBUM_GAIN"]?.parseReplayGainAdjustment()) ?: id3v2["TXXX:REPLAYGAIN_ALBUM_GAIN"]?.parseReplayGainAdjustment())
@@ -0,0 +1,68 @@
/*
* Copyright (c) 2026 Auxio Project
* IndexingProgressCoalescerTest.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.musikr
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Test
class IndexingProgressCoalescerTest {
@Test
fun submit_burstDuringInterval_emitsFirstAndLatestOnFlush() = runTest {
val emitted = mutableListOf<IndexingProgress>()
val coalescer =
IndexingProgressCoalescer(
intervalMs = 250,
clock = { 0L },
onProgress = { emitted.add(it) },
)
val first = IndexingProgress.Songs(loaded = 0, explored = 1)
val latest = IndexingProgress.Songs(loaded = 2, explored = 3)
coalescer.submit(first)
coalescer.submit(IndexingProgress.Songs(loaded = 1, explored = 2))
coalescer.submit(latest)
assertEquals(listOf<IndexingProgress>(first), emitted)
coalescer.flush()
assertEquals(listOf(first, latest), emitted)
}
@Test
fun submit_indeterminate_flushesLatestSongsFirst() = runTest {
val emitted = mutableListOf<IndexingProgress>()
val coalescer =
IndexingProgressCoalescer(
intervalMs = 250,
clock = { 0L },
onProgress = { emitted.add(it) },
)
val first = IndexingProgress.Songs(loaded = 0, explored = 1)
val latest = IndexingProgress.Songs(loaded = 2, explored = 3)
coalescer.submit(first)
coalescer.submit(IndexingProgress.Songs(loaded = 1, explored = 2))
coalescer.submit(latest)
coalescer.submit(IndexingProgress.Indeterminate)
assertEquals(listOf(first, latest, IndexingProgress.Indeterminate), emitted)
}
}
@@ -0,0 +1,74 @@
/*
* Copyright (c) 2026 Auxio Project
* DBCacheTest.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.musikr.cache.db
import android.net.Uri
import io.mockk.coEvery
import io.mockk.every
import io.mockk.mockk
import kotlinx.coroutines.async
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.yield
import org.junit.Assert.assertTrue
import org.junit.Test
import org.oxycblt.musikr.fs.File
class DBCacheTest {
@Test
fun read_initializedMapping_doesNotWaitForMappingLock() = runTest {
val firstUri = mockk<Uri>()
val secondUri = mockk<Uri>()
val readDao = mockk<CacheReadDao>()
coEvery { readDao.selectAllSongs() } returns
listOf(cachedData(firstUri), cachedData(secondUri))
val cache = DBCache.from(readDao)
cache.read(file(firstUri))
val field = DBCache::class.java.getDeclaredField("mappingLock")
field.isAccessible = true
val lock = field.get(cache) as Mutex
lock.lock()
val secondRead = async { cache.read(file(secondUri)) }
try {
yield()
assertTrue(secondRead.isCompleted)
} finally {
lock.unlock()
}
secondRead.await()
}
private fun cachedData(uri: Uri): CachedFileData {
val data = mockk<CachedFileData>(relaxed = true)
every { data.uri } returns uri
every { data.modifiedMs } returns 0L
every { data.addedMs } returns 0L
every { data.mimeType } returns null
return data
}
private fun file(uri: Uri): File {
val file = mockk<File>(relaxed = true)
every { file.uri } returns uri
every { file.modifiedMs } returns 0L
return file
}
}
@@ -0,0 +1,52 @@
/*
* Copyright (c) 2026 Auxio Project
* ValueVolumesTest.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.musikr.fs.path
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotEquals
import org.junit.Test
import org.oxycblt.musikr.fs.Components
class ValueVolumesTest {
@Test
fun internalValue_equalityUsesStableIdentityNotDisplayName() {
val components = Components.parseUnix("/storage/emulated/0")
val value = InternalVolumeValue("external_primary", components, "Phone")
val relabelled = InternalVolumeValue("external_primary", components, "Internal storage")
val different = InternalVolumeValue("different", components, "Phone")
assertEquals(value, relabelled)
assertEquals(value.hashCode(), relabelled.hashCode())
assertNotEquals(value, different)
}
@Test
fun externalValue_equalityIncludesVolumeIdNotDisplayName() {
val components = Components.parseUnix("/storage/7AFE-060A")
val value = ExternalVolumeValue("7AFE-060A", "7afe-060a", components, "SD card")
val relabelled =
ExternalVolumeValue("7AFE-060A", "7afe-060a", components, "Walkman card")
val different =
ExternalVolumeValue("FFFFFFFF-FFFF", "7afe-060a", components, "SD card")
assertEquals(value, relabelled)
assertEquals(value.hashCode(), relabelled.hashCode())
assertNotEquals(value, different)
}
}
@@ -0,0 +1,302 @@
/*
* Copyright (c) 2026 Auxio Project
* PlaylistPathResolverTest.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.musikr.playlist
import android.content.Context
import org.junit.Assert.assertEquals
import org.junit.Test
import org.oxycblt.musikr.fs.Components
import org.oxycblt.musikr.fs.Path
import org.oxycblt.musikr.fs.Volume
class PlaylistPathResolverTest {
@Test
fun resolve_relativeEntries_locksMusicLocationRoot() {
val volume = FakeVolume()
val playlistDir = Path(volume, Components.parseUnix("Music/Playlists"))
val musicRoot = Path(volume, Components.parseUnix("Music"))
val library =
setOf(
Path(volume, Components.parseUnix("Music/Library/Artist/a.mp3")),
Path(volume, Components.parseUnix("Music/Library/Artist/b.mp3")),
)
val entries =
listOf(
PlaylistPathResolver.Entry(
Components.parseUnix("Library/Artist/a.mp3"), absolute = false
),
PlaylistPathResolver.Entry(
Components.parseUnix("Library/Artist/b.mp3"), absolute = false
),
)
val resolved =
PlaylistPathResolver().resolve(entries, listOf(playlistDir, musicRoot)) {
it in library
}
assertEquals(
listOf(
Path(volume, Components.parseUnix("Music/Library/Artist/a.mp3")),
Path(volume, Components.parseUnix("Music/Library/Artist/b.mp3")),
),
resolved,
)
}
@Test
fun resolve_dotPrefixedEntries_resolveLikeBareOnes() {
val volume = FakeVolume()
val playlistDir = Path(volume, Components.parseUnix("Music/Playlists"))
val musicRoot = Path(volume, Components.parseUnix("Music"))
val library =
setOf(
Path(volume, Components.parseUnix("Music/Library/Artist/a.mp3")),
Path(volume, Components.parseUnix("Music/Library/Artist/b.mp3")),
)
val entries =
listOf(
PlaylistPathResolver.Entry(
Components.parseUnix("./Library/Artist/a.mp3"), absolute = false
),
PlaylistPathResolver.Entry(
Components.parseUnix("./Library/Artist/b.mp3"), absolute = false
),
)
val resolved =
PlaylistPathResolver().resolve(entries, listOf(playlistDir, musicRoot)) {
it in library
}
assertEquals(
listOf(
Path(volume, Components.parseUnix("Music/Library/Artist/a.mp3")),
Path(volume, Components.parseUnix("Music/Library/Artist/b.mp3")),
),
resolved,
)
}
@Test
fun resolve_dotdotEntries_escapeThePlaylistDirectory() {
val volume = FakeVolume()
val playlistDir = Path(volume, Components.parseUnix("Music/Playlists"))
val musicRoot = Path(volume, Components.parseUnix("Music"))
val library =
setOf(
Path(volume, Components.parseUnix("Music/Library/Artist/a.mp3")),
Path(volume, Components.parseUnix("Music/Library/Artist/b.mp3")),
)
val entries =
listOf(
PlaylistPathResolver.Entry(
Components.parseUnix("../Library/Artist/a.mp3"), absolute = false
),
PlaylistPathResolver.Entry(
Components.parseUnix("../Library/Artist/b.mp3"), absolute = false
),
)
val resolved =
PlaylistPathResolver().resolve(entries, listOf(playlistDir, musicRoot)) {
it in library
}
assertEquals(
listOf(
Path(volume, Components.parseUnix("Music/Library/Artist/a.mp3")),
Path(volume, Components.parseUnix("Music/Library/Artist/b.mp3")),
),
resolved,
)
}
@Test
fun resolve_ambiguousEntries_lockTheFirstRootInOrder() {
val volume = FakeVolume()
val playlistDir = Path(volume, Components.parseUnix("Music/Playlists"))
val musicRoot = Path(volume, Components.parseUnix("Music"))
val library =
setOf(
Path(volume, Components.parseUnix("Music/Playlists/Library/Artist/a.mp3")),
Path(volume, Components.parseUnix("Music/Library/Artist/a.mp3")),
)
val entries =
listOf(
PlaylistPathResolver.Entry(
Components.parseUnix("Library/Artist/a.mp3"), absolute = false
)
)
val resolved =
PlaylistPathResolver().resolve(entries, listOf(playlistDir, musicRoot)) {
it in library
}
assertEquals(
listOf(Path(volume, Components.parseUnix("Music/Playlists/Library/Artist/a.mp3"))),
resolved,
)
}
@Test
fun resolve_foreignAbsoluteEntries_stripLeadingSegmentsToLock() {
val volume = FakeVolume()
val playlistDir = Path(volume, Components.parseUnix("Music/Playlists"))
val musicRoot = Path(volume, Components.parseUnix("Music"))
val library =
setOf(
Path(volume, Components.parseUnix("Music/Library/Artist/a.mp3")),
Path(volume, Components.parseUnix("Music/Library/Artist/b.mp3")),
)
// Written on another machine: C:\Users\me\Music\... with the volume prefix consumed.
val entries =
listOf(
PlaylistPathResolver.Entry(
Components.parseWindows("Users\\me\\Music\\Library\\Artist\\a.mp3"),
absolute = true,
),
PlaylistPathResolver.Entry(
Components.parseWindows("Users\\me\\Music\\Library\\Artist\\b.mp3"),
absolute = true,
),
)
val resolved =
PlaylistPathResolver().resolve(entries, listOf(playlistDir, musicRoot)) {
it in library
}
assertEquals(
listOf(
Path(volume, Components.parseUnix("Music/Library/Artist/a.mp3")),
Path(volume, Components.parseUnix("Music/Library/Artist/b.mp3")),
),
resolved,
)
}
@Test
fun resolve_partiallyMissingEntries_resolveTheSurvivors() {
val volume = FakeVolume()
val playlistDir = Path(volume, Components.parseUnix("Music/Playlists"))
val musicRoot = Path(volume, Components.parseUnix("Music"))
val library =
setOf(
Path(volume, Components.parseUnix("Music/Library/Artist/a.mp3")),
Path(volume, Components.parseUnix("Music/Library/Artist/c.mp3")),
)
val entries =
listOf(
PlaylistPathResolver.Entry(
Components.parseUnix("Library/Artist/a.mp3"), absolute = false
),
PlaylistPathResolver.Entry(
Components.parseUnix("Library/Artist/b.mp3"), absolute = false
),
PlaylistPathResolver.Entry(
Components.parseUnix("Library/Artist/c.mp3"), absolute = false
),
)
val resolved =
PlaylistPathResolver().resolve(entries, listOf(playlistDir, musicRoot)) {
it in library
}
assertEquals(
listOf(
Path(volume, Components.parseUnix("Music/Library/Artist/a.mp3")),
Path(volume, Components.parseUnix("Music/Library/Artist/c.mp3")),
),
resolved,
)
}
@Test
fun resolve_firstEntryMissing_probeAdvancesAndLocks() {
val volume = FakeVolume()
val playlistDir = Path(volume, Components.parseUnix("Music/Playlists"))
val musicRoot = Path(volume, Components.parseUnix("Music"))
val library =
setOf(
Path(volume, Components.parseUnix("Music/Library/Artist/b.mp3")),
Path(volume, Components.parseUnix("Music/Library/Artist/c.mp3")),
)
val entries =
listOf(
PlaylistPathResolver.Entry(
Components.parseUnix("Library/Artist/a.mp3"), absolute = false
),
PlaylistPathResolver.Entry(
Components.parseUnix("Library/Artist/b.mp3"), absolute = false
),
PlaylistPathResolver.Entry(
Components.parseUnix("Library/Artist/c.mp3"), absolute = false
),
)
val resolved =
PlaylistPathResolver().resolve(entries, listOf(playlistDir, musicRoot)) {
it in library
}
assertEquals(
listOf(
Path(volume, Components.parseUnix("Music/Library/Artist/b.mp3")),
Path(volume, Components.parseUnix("Music/Library/Artist/c.mp3")),
),
resolved,
)
}
@Test
fun resolve_unresolvableEntries_failAsNull() {
val volume = FakeVolume()
val playlistDir = Path(volume, Components.parseUnix("Music/Playlists"))
val musicRoot = Path(volume, Components.parseUnix("Music"))
val library =
setOf(Path(volume, Components.parseUnix("Music/Library/Artist/a.mp3")))
val entries =
listOf(
PlaylistPathResolver.Entry(
Components.parseUnix("Elsewhere/Artist/x.mp3"), absolute = false
),
PlaylistPathResolver.Entry(
Components.parseUnix("Elsewhere/Artist/y.mp3"), absolute = false
),
)
val resolved =
PlaylistPathResolver().resolve(entries, listOf(playlistDir, musicRoot)) {
it in library
}
assertEquals(null, resolved)
}
private class FakeVolume : Volume.External {
override val mediaStoreName = "fake"
override val id = "fake"
override val components = Components.parseUnix("storage/emulated/0")
override fun resolveName(context: Context) = "fake"
}
}
@@ -0,0 +1,92 @@
/*
* Copyright (c) 2026 Auxio Project
* PlaylistReconcilerTest.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.musikr.playlist
import org.junit.Assert.assertEquals
import org.junit.Test
import org.oxycblt.musikr.Music
class PlaylistReconcilerTest {
@Test
fun reconcile_unchangedFile_keepsTheStoredPlaylist() {
val tracked = tracked(42L)
val discovered = discovered(42L, resolvedCount = 1)
val actions = PlaylistReconciler.reconcile(listOf(tracked), listOf(discovered))
assertEquals(listOf(PlaylistReconciler.Action.Keep(tracked)), actions)
}
@Test
fun reconcile_changedFile_replacesTheStoredPlaylist() {
val tracked = tracked(42L)
val discovered = discovered(43L, resolvedCount = 1)
val actions = PlaylistReconciler.reconcile(listOf(tracked), listOf(discovered))
assertEquals(listOf(PlaylistReconciler.Action.Replace(tracked, discovered)), actions)
}
@Test
fun reconcile_deletedFile_keepsTheStoredPlaylist() {
val tracked = tracked(42L)
val actions = PlaylistReconciler.reconcile(listOf(tracked), emptyList())
assertEquals(listOf(PlaylistReconciler.Action.Keep(tracked)), actions)
}
@Test
fun reconcile_changedFileWithNothingResolved_keepsTheStoredPlaylist() {
val tracked = tracked(42L)
val discovered = discovered(43L, resolvedCount = 0)
val actions = PlaylistReconciler.reconcile(listOf(tracked), listOf(discovered))
assertEquals(listOf(PlaylistReconciler.Action.Keep(tracked)), actions)
}
@Test
fun reconcile_newFile_createsATrackedPlaylist() {
val discovered = discovered(42L, resolvedCount = 1)
val actions = PlaylistReconciler.reconcile(emptyList(), listOf(discovered))
assertEquals(listOf(PlaylistReconciler.Action.Create(discovered)), actions)
}
@Test
fun reconcile_newFileWithNothingResolved_doesNothing() {
val discovered = discovered(42L, resolvedCount = 0)
val actions = PlaylistReconciler.reconcile(emptyList(), listOf(discovered))
assertEquals(emptyList<PlaylistReconciler.Action>(), actions)
}
private fun tracked(signature: Long) =
PlaylistReconciler.Tracked(
Music.UID.auxio(Music.UID.Item.PLAYLIST),
"content://tree/playlists/x.m3u",
signature,
)
private fun discovered(signature: Long, resolvedCount: Int) =
PlaylistReconciler.Discovered("content://tree/playlists/x.m3u", signature, resolvedCount)
}
@@ -0,0 +1,70 @@
/*
* Copyright (c) 2026 Auxio Project
* M3UTest.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.musikr.playlist.m3u
import org.junit.Assert.assertEquals
import org.junit.Test
import org.oxycblt.musikr.fs.Components
import org.oxycblt.musikr.playlist.PlaylistPathResolver
class M3UTest {
@Test
fun read_relativeAndForeignAbsoluteLines_produceEntries() {
val text =
"""
#EXTM3U
Library/Artist/a.mp3
./Library/Artist/b.mp3
C:\Users\me\Music\Library\Artist\c.mp3
"""
.trimIndent()
val imported = M3U.new().read(text.byteInputStream())
assertEquals(
listOf(
PlaylistPathResolver.Entry(
Components.parseUnix("Library/Artist/a.mp3"), absolute = false
),
PlaylistPathResolver.Entry(
Components.parseUnix("./Library/Artist/b.mp3"), absolute = false
),
PlaylistPathResolver.Entry(
Components.parseUnix("Users/me/Music/Library/Artist/c.mp3"), absolute = true
),
),
imported?.entries,
)
}
@Test
fun read_playlistMetadata_producesName() {
val text =
"""
#EXTM3U
#PLAYLIST:My Mix
Library/Artist/a.mp3
"""
.trimIndent()
val imported = M3U.new().read(text.byteInputStream())
assertEquals("My Mix", imported?.name)
}
}
@@ -0,0 +1,266 @@
/*
* Copyright (c) 2026 Auxio Project
* LibrarySnapshotCaptureTest.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.musikr.snapshot
import android.net.Uri
import io.mockk.coEvery
import io.mockk.every
import io.mockk.mockk
import java.io.File
import java.io.IOException
import java.nio.file.AtomicMoveNotSupportedException
import java.nio.file.Files
import kotlin.coroutines.cancellation.CancellationException
import kotlinx.coroutines.Job
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import org.junit.Assert.assertEquals
import org.junit.Assert.assertThrows
import org.junit.Test
import org.junit.runner.RunWith
import org.oxycblt.musikr.Config
import org.oxycblt.musikr.Interpretation
import org.oxycblt.musikr.Library
import org.oxycblt.musikr.Music
import org.oxycblt.musikr.Song
import org.oxycblt.musikr.Storage
import org.oxycblt.musikr.fs.Components
import org.oxycblt.musikr.fs.Format
import org.oxycblt.musikr.fs.Path
import org.oxycblt.musikr.fs.path.InternalVolumeValue
import org.oxycblt.musikr.playlist.PlaylistFile
import org.oxycblt.musikr.playlist.PlaylistHandle
import org.oxycblt.musikr.playlist.SongPointer
import org.oxycblt.musikr.playlist.db.StoredPlaylists
import org.oxycblt.musikr.playlist.interpret.PlaylistInterpreter
import org.oxycblt.musikr.tag.ReleaseType
import org.oxycblt.musikr.tag.ReplayGainAdjustment
import org.oxycblt.musikr.tag.interpret.Naming
import org.oxycblt.musikr.tag.interpret.PreAlbum
import org.oxycblt.musikr.tag.interpret.PreArtist
import org.oxycblt.musikr.tag.interpret.PreArtistsFrom
import org.oxycblt.musikr.tag.interpret.PreGenre
import org.oxycblt.musikr.tag.interpret.PreSong
import org.oxycblt.musikr.tag.interpret.Separators
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config as RobolectricConfig
@RunWith(RobolectricTestRunner::class)
@RobolectricConfig(sdk = [30])
class LibrarySnapshotCaptureTest {
@Test
fun capture_completeLibrary_restoresEquivalentGraph() = runBlocking {
val storedPlaylists = mockk<StoredPlaylists>()
val interpretation = Interpretation(Naming.simple(), Separators.from(""))
val config = Config(mockk(), Storage(mockk(), mockk(), storedPlaylists), interpretation)
val playlistInterpreter = PlaylistInterpreter.new(interpretation)
val input = preSong(91, "Captured")
val handle = TestPlaylistHandle(playlistUid(91))
coEvery { storedPlaylists.read() } returns
listOf(PlaylistFile("Bangers", listOf(SongPointer.UID(input.v363Uid)), handle))
val original =
runBlocking {
LibrarySnapshotGraph.restore(
listOf(input),
storedPlaylists,
playlistInterpreter,
)
}
val directory = Files.createTempDirectory("auxio-capture").toFile().apply { deleteOnExit() }
val store = LibrarySnapshotStore(directory)
val snapshot = LibrarySnapshot(RuntimeEnvironment.getApplication(), config)
val fingerprint = fingerprint()
snapshot.capture(original, store, fingerprint)
val restored = requireNotNull(snapshot.restore(store, fingerprint))
assertEquals(original.songs, restored.songs)
assertEquals(original.albums, restored.albums)
assertEquals(original.artists, restored.artists)
assertEquals(original.genres, restored.genres)
assertEquals(original.playlists, restored.playlists)
assertEquals(listOf("library.snapshot"), directory.listFiles()!!.map { it.name })
}
@Test
fun capture_partialFailureCancellationOrMoveFailure_preservesPreviousValidGraph() =
runBlocking {
val storedPlaylists = mockk<StoredPlaylists>()
val interpretation = Interpretation(Naming.simple(), Separators.from(""))
val config = Config(mockk(), Storage(mockk(), mockk(), storedPlaylists), interpretation)
val playlistInterpreter = PlaylistInterpreter.new(interpretation)
val originalInput = preSong(91, "Captured")
val updatedInput = preSong(91, "Replacement")
val handle = TestPlaylistHandle(playlistUid(91))
val liveFile =
PlaylistFile(
"Bangers",
listOf(SongPointer.UID(originalInput.v363Uid)),
handle,
)
coEvery { storedPlaylists.read() } returns listOf(liveFile)
val original =
LibrarySnapshotGraph.restore(
listOf(originalInput),
storedPlaylists,
playlistInterpreter,
)
val updated =
LibrarySnapshotGraph.restore(
listOf(updatedInput),
storedPlaylists,
playlistInterpreter,
)
val directory =
Files.createTempDirectory("auxio-capture-failure").toFile().apply { deleteOnExit() }
val store = LibrarySnapshotStore(directory)
val snapshot = LibrarySnapshot(RuntimeEnvironment.getApplication(), config)
val fingerprint = fingerprint()
snapshot.capture(original, store, fingerprint)
val partialLibrary = mockk<Library>()
every { partialLibrary.songs } returns listOf(mockk<Song>())
assertSuspendThrows<IllegalArgumentException> {
snapshot.capture(partialLibrary, store, fingerprint)
}
assertPreserved(snapshot, store, fingerprint, original, directory)
coEvery { storedPlaylists.read() } throws IOException("Forced verification failure")
assertSuspendThrows<IOException> {
snapshot.capture(updated, store, fingerprint)
}
coEvery { storedPlaylists.read() } returns listOf(liveFile)
assertPreserved(snapshot, store, fingerprint, original, directory)
val failedMoveStore =
LibrarySnapshotStore(directory) { source, target ->
throw AtomicMoveNotSupportedException(
source.toString(),
target.toString(),
"Forced capture move failure",
)
}
assertSuspendThrows<AtomicMoveNotSupportedException> {
snapshot.capture(updated, failedMoveStore, fingerprint)
}
assertPreserved(snapshot, store, fingerprint, original, directory)
val cancelled = Job().apply { cancel() }
assertSuspendThrows<CancellationException> {
withContext(cancelled) { snapshot.capture(updated, store, fingerprint) }
}
assertPreserved(snapshot, store, fingerprint, original, directory)
}
private inline fun <reified T : Throwable> assertSuspendThrows(
noinline block: suspend () -> Unit
) {
assertThrows(T::class.java) { runBlocking { block() } }
}
private suspend fun assertPreserved(
snapshot: LibrarySnapshot,
store: LibrarySnapshotStore,
fingerprint: LibrarySnapshotFingerprint,
original: Library,
directory: File,
) {
val restored = requireNotNull(snapshot.restore(store, fingerprint))
assertEquals(original.songs, restored.songs)
assertEquals(original.playlists, restored.playlists)
assertEquals(listOf("library.snapshot"), directory.listFiles()!!.map { it.name })
}
private fun fingerprint() =
LibrarySnapshotFingerprint(
sourceMode = "SAF",
sourceRoots = listOf("content://tree/Development/Music"),
excludedRoots = emptyList(),
withHidden = false,
excludeNonMusic = false,
intelligentSorting = true,
separators = ",;",
coverMode = "BALANCED",
)
private fun preSong(suffix: Int, name: String): PreSong {
val artist = PreArtist(null, Naming.simple().name("Artist", null), "Artist")
return PreSong(
v363Uid = songUid(suffix),
v400Uid = songUid(suffix + 1_000),
v401Uid = songUid(suffix + 2_000),
musicBrainzId = null,
name = Naming.simple().name(name, null),
rawName = name,
track = 1,
disc = null,
date = null,
uri = Uri.parse("content://snapshot/${songUid(suffix)}"),
path =
Path(
InternalVolumeValue(
null,
Components.parseUnix("/storage/emulated/0"),
"Internal shared storage",
),
Components.parseUnix("Download/$name.mp3"),
),
format = Format.MPEG3,
size = 1_024L,
durationMs = 60_000L,
bitrateKbps = 128,
sampleRateHz = 44_100,
replayGainAdjustment = ReplayGainAdjustment(null, null),
modifiedMs = 100L,
addedMs = 200L,
cover = null,
preAlbum =
PreAlbum(
null,
Naming.simple().name("Album", null),
"Album",
ReleaseType.Album(null),
PreArtistsFrom.Album(listOf(artist)),
),
preArtists = listOf(artist),
preGenres = listOf(PreGenre(Naming.simple().name("Genre", null), "Genre")),
)
}
private fun songUid(suffix: Int) =
requireNotNull(
Music.UID.fromString("uas00000000-0000-4000-8000-${suffix.toString().padStart(12, '0')}")
)
private fun playlistUid(suffix: Int) =
requireNotNull(
Music.UID.fromString("uap00000000-0000-4000-8000-${suffix.toString().padStart(12, '0')}")
)
private class TestPlaylistHandle(override val uid: Music.UID) : PlaylistHandle {
override suspend fun rename(name: String) {}
override suspend fun add(songs: List<Song>) {}
override suspend fun rewrite(songs: List<Song>) {}
override suspend fun delete() {}
}
}
@@ -0,0 +1,439 @@
/*
* Copyright (c) 2026 Auxio Project
* LibrarySnapshotCodecTest.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.musikr.snapshot
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.DataOutputStream
import java.io.EOFException
import java.io.IOException
import java.util.UUID
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertThrows
import org.junit.Test
import org.oxycblt.musikr.Music
import org.oxycblt.musikr.fs.Components
import org.oxycblt.musikr.fs.Path
import org.oxycblt.musikr.fs.path.ExternalVolumeValue
import org.oxycblt.musikr.fs.path.InternalVolumeValue
import org.oxycblt.musikr.tag.Date
import org.oxycblt.musikr.tag.Disc
import org.oxycblt.musikr.tag.ReleaseType
import org.oxycblt.musikr.tag.ReplayGainAdjustment
class LibrarySnapshotCodecTest {
@Test
fun header_roundTrip_preservesMagicAndSchemaVersion() {
val output = ByteArrayOutputStream()
LibrarySnapshotCodec.writeHeader(output)
val header = LibrarySnapshotCodec.readHeader(ByteArrayInputStream(output.toByteArray()))
assertEquals(LibrarySnapshotCodec.MAGIC, header.magic)
assertEquals(1, header.schemaVersion)
}
@Test
fun readHeader_unknownMagic_throwsIOException() {
val output = ByteArrayOutputStream()
LibrarySnapshotCodec.writeHeader(output)
val bytes = output.toByteArray()
bytes[0] = 'X'.code.toByte()
assertThrows(IOException::class.java) {
LibrarySnapshotCodec.readHeader(ByteArrayInputStream(bytes))
}
}
@Test
fun readHeader_unknownSchemaVersion_throwsIOException() {
val output = ByteArrayOutputStream()
LibrarySnapshotCodec.writeHeader(output)
val bytes = output.toByteArray()
bytes[bytes.lastIndex] = 2.toByte()
assertThrows(IOException::class.java) {
LibrarySnapshotCodec.readHeader(ByteArrayInputStream(bytes))
}
}
@Test
fun readHeader_truncatedSchemaVersion_throwsEOFException() {
val output = ByteArrayOutputStream()
LibrarySnapshotCodec.writeHeader(output)
val bytes = output.toByteArray()
val truncated = bytes.copyOf(bytes.size - 1)
assertThrows(EOFException::class.java) {
LibrarySnapshotCodec.readHeader(ByteArrayInputStream(truncated))
}
}
@Test
fun string_roundTrip_preservesUtf8Text() {
val value = "Album 初音ミク 🎵"
val output = ByteArrayOutputStream()
LibrarySnapshotCodec.writeString(output, value)
val decoded = LibrarySnapshotCodec.readString(ByteArrayInputStream(output.toByteArray()))
assertEquals(value, decoded)
}
@Test
fun readString_invalidLengths_throwIOException() {
for (byteCount in listOf(-1, 1024 * 1024 + 1)) {
val output = ByteArrayOutputStream()
DataOutputStream(output).writeInt(byteCount)
assertThrows(IOException::class.java) {
LibrarySnapshotCodec.readString(ByteArrayInputStream(output.toByteArray()))
}
}
}
@Test
fun readString_truncatedPayload_throwsEOFException() {
val output = ByteArrayOutputStream()
LibrarySnapshotCodec.writeString(output, "truncated")
val bytes = output.toByteArray()
val truncated = bytes.copyOf(bytes.size - 1)
assertThrows(EOFException::class.java) {
LibrarySnapshotCodec.readString(ByteArrayInputStream(truncated))
}
}
@Test
fun readString_malformedUtf8_throwsIOException() {
val output = ByteArrayOutputStream()
val dataOutput = DataOutputStream(output)
dataOutput.writeInt(1)
dataOutput.writeByte(0x80)
assertThrows(IOException::class.java) {
LibrarySnapshotCodec.readString(ByteArrayInputStream(output.toByteArray()))
}
}
@Test
fun nullableString_roundTrip_distinguishesNullEmptyAndText() {
val output = ByteArrayOutputStream()
LibrarySnapshotCodec.writeNullableString(output, null)
LibrarySnapshotCodec.writeNullableString(output, "")
LibrarySnapshotCodec.writeNullableString(output, "Queue 初音ミク")
val input = ByteArrayInputStream(output.toByteArray())
assertNull(LibrarySnapshotCodec.readNullableString(input))
assertEquals("", LibrarySnapshotCodec.readNullableString(input))
assertEquals("Queue 初音ミク", LibrarySnapshotCodec.readNullableString(input))
}
@Test
fun readNullableString_invalidMarker_throwsIOException() {
val output = ByteArrayOutputStream()
output.write(2)
LibrarySnapshotCodec.writeString(output, "still present")
assertThrows(IOException::class.java) {
LibrarySnapshotCodec.readNullableString(ByteArrayInputStream(output.toByteArray()))
}
}
@Test
fun integer_roundTrip_preservesBoundaries() {
val output = ByteArrayOutputStream()
LibrarySnapshotCodec.writeInt(output, Int.MIN_VALUE)
LibrarySnapshotCodec.writeInt(output, Int.MAX_VALUE)
LibrarySnapshotCodec.writeLong(output, Long.MIN_VALUE)
LibrarySnapshotCodec.writeLong(output, Long.MAX_VALUE)
val input = ByteArrayInputStream(output.toByteArray())
assertEquals(Int.MIN_VALUE, LibrarySnapshotCodec.readInt(input))
assertEquals(Int.MAX_VALUE, LibrarySnapshotCodec.readInt(input))
assertEquals(Long.MIN_VALUE, LibrarySnapshotCodec.readLong(input))
assertEquals(Long.MAX_VALUE, LibrarySnapshotCodec.readLong(input))
}
@Test
fun float_roundTrip_preservesValues() {
val values =
listOf(
0.0f,
-0.0f,
-123.5f,
Float.MIN_VALUE,
Float.MAX_VALUE,
Float.NEGATIVE_INFINITY,
Float.POSITIVE_INFINITY,
Float.NaN,
)
val output = ByteArrayOutputStream()
values.forEach { LibrarySnapshotCodec.writeFloat(output, it) }
val input = ByteArrayInputStream(output.toByteArray())
val decoded = values.map { LibrarySnapshotCodec.readFloat(input) }
assertEquals(values, decoded)
}
@Test
fun boolean_roundTrip_preservesFalseAndTrue() {
val output = ByteArrayOutputStream()
LibrarySnapshotCodec.writeBoolean(output, false)
LibrarySnapshotCodec.writeBoolean(output, true)
val input = ByteArrayInputStream(output.toByteArray())
assertEquals(false, LibrarySnapshotCodec.readBoolean(input))
assertEquals(true, LibrarySnapshotCodec.readBoolean(input))
}
@Test
fun nullableFloat_roundTrip_distinguishesNullAndZero() {
val values = listOf<Float?>(null, 0.0f, -6.5f)
val output = ByteArrayOutputStream()
values.forEach { LibrarySnapshotCodec.writeNullableFloat(output, it) }
val input = ByteArrayInputStream(output.toByteArray())
val decoded = values.map { LibrarySnapshotCodec.readNullableFloat(input) }
assertEquals(values, decoded)
}
@Test
fun primitives_truncatedInput_throwEOFException() {
assertThrows(EOFException::class.java) {
LibrarySnapshotCodec.readInt(ByteArrayInputStream(ByteArray(3)))
}
assertThrows(EOFException::class.java) {
LibrarySnapshotCodec.readLong(ByteArrayInputStream(ByteArray(7)))
}
assertThrows(EOFException::class.java) {
LibrarySnapshotCodec.readFloat(ByteArrayInputStream(ByteArray(3)))
}
assertThrows(EOFException::class.java) {
LibrarySnapshotCodec.readBoolean(ByteArrayInputStream(ByteArray(0)))
}
}
@Test
fun collectionCount_codec_enforcesCallerMaximum() {
val output = ByteArrayOutputStream()
LibrarySnapshotCodec.writeCount(output, 3, maximum = 5)
assertEquals(
3,
LibrarySnapshotCodec.readCount(ByteArrayInputStream(output.toByteArray()), maximum = 5),
)
assertThrows(IllegalArgumentException::class.java) {
LibrarySnapshotCodec.writeCount(ByteArrayOutputStream(), -1, maximum = 5)
}
assertThrows(IllegalArgumentException::class.java) {
LibrarySnapshotCodec.writeCount(ByteArrayOutputStream(), 6, maximum = 5)
}
for (count in listOf(-1, 6)) {
val invalid = ByteArrayOutputStream()
DataOutputStream(invalid).writeInt(count)
assertThrows(IOException::class.java) {
LibrarySnapshotCodec.readCount(
ByteArrayInputStream(invalid.toByteArray()),
maximum = 5,
)
}
}
}
@Test
fun readBoolean_invalidMarker_throwsIOException() {
assertThrows(IOException::class.java) {
LibrarySnapshotCodec.readBoolean(ByteArrayInputStream(byteArrayOf(2)))
}
}
@Test
fun uid_roundTrip_preservesCanonicalRepresentation() {
val uid =
requireNotNull(
Music.UID.fromString("uas00112233-4455-6677-8899-aabbccddeeff")
)
val output = ByteArrayOutputStream()
LibrarySnapshotCodec.writeUid(output, uid)
val decoded = LibrarySnapshotCodec.readUid(ByteArrayInputStream(output.toByteArray()))
assertEquals(uid, decoded)
}
@Test
fun date_roundTrip_preservesFullPrecision() {
val date = requireNotNull(Date.from("2016-08-16T00:01:02Z"))
val output = ByteArrayOutputStream()
LibrarySnapshotCodec.writeDate(output, date)
val decoded = LibrarySnapshotCodec.readDate(ByteArrayInputStream(output.toByteArray()))
assertEquals(date, decoded)
}
@Test
fun disc_roundTrip_preservesNumberAndSubtitle() {
val disc = Disc(2, "Bonus 界")
val output = ByteArrayOutputStream()
LibrarySnapshotCodec.writeDisc(output, disc)
val decoded = LibrarySnapshotCodec.readDisc(ByteArrayInputStream(output.toByteArray()))
assertEquals(disc.number, decoded.number)
assertEquals(disc.name, decoded.name)
}
@Test
fun releaseType_roundTrip_preservesTypeAndRefinement() {
val values =
listOf<ReleaseType>(
ReleaseType.Album(null),
ReleaseType.Album(ReleaseType.Refinement.LIVE),
ReleaseType.EP(ReleaseType.Refinement.REMIX),
ReleaseType.Single(null),
ReleaseType.Compilation(ReleaseType.Refinement.LIVE),
ReleaseType.Soundtrack,
ReleaseType.Mix,
ReleaseType.Mixtape,
ReleaseType.Demo,
)
val output = ByteArrayOutputStream()
values.forEach { LibrarySnapshotCodec.writeReleaseType(output, it) }
val input = ByteArrayInputStream(output.toByteArray())
val decoded = values.map { LibrarySnapshotCodec.readReleaseType(input) }
assertEquals(values, decoded)
}
@Test
fun replayGain_roundTrip_preservesIndependentTrackAndAlbumValues() {
val values =
listOf(
ReplayGainAdjustment(track = -6.5f, album = null),
ReplayGainAdjustment(track = null, album = -9.0f),
)
val output = ByteArrayOutputStream()
values.forEach { LibrarySnapshotCodec.writeReplayGainAdjustment(output, it) }
val input = ByteArrayInputStream(output.toByteArray())
val decoded = values.map { LibrarySnapshotCodec.readReplayGainAdjustment(input) }
assertEquals(values, decoded)
}
@Test
fun musicBrainzId_roundTrip_preservesNullableUuids() {
val values =
listOf<UUID?>(
null,
UUID.fromString("00112233-4455-6677-8899-aabbccddeeff"),
UUID.fromString("ffeeddcc-bbaa-9988-7766-554433221100"),
)
val output = ByteArrayOutputStream()
values.forEach { LibrarySnapshotCodec.writeMusicBrainzId(output, it) }
val input = ByteArrayInputStream(output.toByteArray())
val decoded = values.map { LibrarySnapshotCodec.readMusicBrainzId(input) }
assertEquals(values, decoded)
}
@Test
fun path_roundTrip_preservesSharedVolumesAndComponents() {
val paths =
listOf(
Path(
InternalVolumeValue(
"external_primary",
Components.parseUnix("/storage/emulated/0"),
"Phone",
),
Components.parseUnix("Library/A/song.mp3"),
),
Path(
ExternalVolumeValue(
"7AFE-060A",
"7afe-060a",
Components.parseUnix("/storage/7AFE-060A"),
"SD card",
),
Components.parseUnix("Development/Music/song.mp3"),
),
)
val output = ByteArrayOutputStream()
paths.forEach { LibrarySnapshotCodec.writePath(output, it) }
val input = ByteArrayInputStream(output.toByteArray())
val decoded = paths.map { LibrarySnapshotCodec.readPath(input) }
assertEquals(paths, decoded)
assertEquals("Phone", (decoded[0].volume as InternalVolumeValue).displayName)
assertEquals("SD card", (decoded[1].volume as ExternalVolumeValue).displayName)
}
@Test
fun domainCodecs_invalidEncodings_throwIOException() {
val invalidText = ByteArrayOutputStream()
LibrarySnapshotCodec.writeString(invalidText, "not-a-domain-value")
assertThrows(IOException::class.java) {
LibrarySnapshotCodec.readUid(ByteArrayInputStream(invalidText.toByteArray()))
}
assertThrows(IOException::class.java) {
LibrarySnapshotCodec.readDate(ByteArrayInputStream(invalidText.toByteArray()))
}
fun taggedInput(): ByteArrayInputStream {
val output = ByteArrayOutputStream()
LibrarySnapshotCodec.writeInt(output, 99)
return ByteArrayInputStream(output.toByteArray())
}
assertThrows(IOException::class.java) {
LibrarySnapshotCodec.readReleaseType(taggedInput())
}
assertThrows(IOException::class.java) { LibrarySnapshotCodec.readPath(taggedInput()) }
assertThrows(IOException::class.java) { LibrarySnapshotCodec.readFormat(taggedInput()) }
val invalidRefinement = ByteArrayOutputStream()
LibrarySnapshotCodec.writeInt(invalidRefinement, 0)
LibrarySnapshotCodec.writeNullableString(invalidRefinement, "SYNCHRONIZED")
assertThrows(IOException::class.java) {
LibrarySnapshotCodec.readReleaseType(
ByteArrayInputStream(invalidRefinement.toByteArray())
)
}
val excessiveNesting = ByteArrayOutputStream()
repeat(10) {
LibrarySnapshotCodec.writeInt(excessiveNesting, 1)
LibrarySnapshotCodec.writeBoolean(excessiveNesting, true)
}
assertThrows(IOException::class.java) {
LibrarySnapshotCodec.readFormat(
ByteArrayInputStream(excessiveNesting.toByteArray())
)
}
}
}
@@ -0,0 +1,146 @@
/*
* Copyright (c) 2026 Auxio Project
* LibrarySnapshotCoversTest.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.musikr.snapshot
import android.net.Uri
import java.io.File
import java.io.FileNotFoundException
import java.nio.file.Files
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.oxycblt.musikr.covers.CoverResult
import org.oxycblt.musikr.covers.fs.FSCovers
import org.oxycblt.musikr.covers.stored.CoverStorage
import org.oxycblt.musikr.covers.stored.StoredCovers
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [30])
class LibrarySnapshotCoversTest {
@Test
fun absentCover_restore_returnsNullWithoutCreatingStorage() {
val root = Files.createTempDirectory("auxio-snapshot-covers").toFile().apply { deleteOnExit() }
val storedCoverDirectory = File(root, "covers")
val context = RuntimeEnvironment.getApplication()
val restored =
LibrarySnapshotCovers.restore(
id = null,
storedCoverDirectory = storedCoverDirectory,
context = context,
)
assertNull(restored)
assertFalse(storedCoverDirectory.exists())
}
@Test
fun storedCover_restore_preservesLiveIdentityEqualityAndHashCode() {
val storedCoverDirectory =
Files.createTempDirectory("auxio-stored-cover").toFile().apply { deleteOnExit() }
File(storedCoverDirectory, "cover.webp").writeBytes(byteArrayOf(1, 2, 3))
val id = "mcs:cover.webp"
val context = RuntimeEnvironment.getApplication()
val live =
runBlocking {
when (val result = StoredCovers(CoverStorage.at(storedCoverDirectory)).obtain(id)) {
is CoverResult.Hit -> result.cover
is CoverResult.Miss -> error("Expected existing stored cover")
}
}
val restored =
requireNotNull(
LibrarySnapshotCovers.restore(
id = id,
storedCoverDirectory = storedCoverDirectory,
context = context,
)
)
assertEquals(id, restored.id)
assertEquals(live, restored)
assertEquals(restored, live)
assertEquals(live.hashCode(), restored.hashCode())
}
@Test
fun folderCover_restoreAfterDeletion_preservesLiveIdentityEqualityAndHashCode() {
val root = Files.createTempDirectory("auxio-folder-cover").toFile().apply { deleteOnExit() }
val storedCoverDirectory = File(root, "covers")
val coverFile = File(root, "folder.jpg").apply { writeBytes(byteArrayOf(4, 5, 6)) }
val id = "mcf:${Uri.fromFile(coverFile)}"
val context = RuntimeEnvironment.getApplication()
val live =
runBlocking {
when (val result = FSCovers(context).obtain(id)) {
is CoverResult.Hit -> result.cover
is CoverResult.Miss -> error("Expected existing folder cover")
}
}
assertTrue(coverFile.delete())
val restored =
requireNotNull(
LibrarySnapshotCovers.restore(
id = id,
storedCoverDirectory = storedCoverDirectory,
context = context,
)
)
assertFalse(coverFile.exists())
assertFalse(storedCoverDirectory.exists())
assertEquals(id, restored.id)
assertEquals(live, restored)
assertEquals(restored, live)
assertEquals(live.hashCode(), restored.hashCode())
}
@Test
fun deletedStoredCover_restore_succeedsAndOpenFailsLazily() {
val storedCoverDirectory =
Files.createTempDirectory("auxio-deleted-cover").toFile().apply { deleteOnExit() }
val coverFile = File(storedCoverDirectory, "deleted.webp")
coverFile.writeBytes(byteArrayOf(7, 8, 9))
assertTrue(coverFile.delete())
val id = "mcs:deleted.webp"
val context = RuntimeEnvironment.getApplication()
val restored =
requireNotNull(
LibrarySnapshotCovers.restore(
id = id,
storedCoverDirectory = storedCoverDirectory,
context = context,
)
)
assertEquals(id, restored.id)
assertThrows(FileNotFoundException::class.java) { runBlocking { restored.open() } }
}
}
@@ -0,0 +1,345 @@
/*
* Copyright (c) 2026 Auxio Project
* LibrarySnapshotDocumentTest.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.musikr.snapshot
import android.net.Uri
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.every
import io.mockk.mockk
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.EOFException
import java.io.IOException
import java.io.InputStream
import java.nio.file.Files
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Assert.assertSame
import org.junit.Assert.assertThrows
import org.junit.Test
import org.junit.runner.RunWith
import org.oxycblt.musikr.Music
import org.oxycblt.musikr.Song
import org.oxycblt.musikr.fs.Components
import org.oxycblt.musikr.fs.Format
import org.oxycblt.musikr.fs.Path
import org.oxycblt.musikr.fs.path.InternalVolumeValue
import org.oxycblt.musikr.playlist.PlaylistFile
import org.oxycblt.musikr.playlist.PlaylistHandle
import org.oxycblt.musikr.playlist.SongPointer
import org.oxycblt.musikr.playlist.db.StoredPlaylists
import org.oxycblt.musikr.playlist.interpret.PlaylistInterpreter
import org.oxycblt.musikr.playlist.interpret.PrePlaylist
import org.oxycblt.musikr.tag.ReleaseType
import org.oxycblt.musikr.tag.ReplayGainAdjustment
import org.oxycblt.musikr.tag.interpret.Naming
import org.oxycblt.musikr.tag.interpret.PreAlbum
import org.oxycblt.musikr.tag.interpret.PreArtist
import org.oxycblt.musikr.tag.interpret.PreArtistsFrom
import org.oxycblt.musikr.tag.interpret.PreGenre
import org.oxycblt.musikr.tag.interpret.PreSong
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [30])
class LibrarySnapshotDocumentTest {
private companion object {
val TEST_FINGERPRINT =
LibrarySnapshotFingerprint(
"TEST",
emptyList(),
emptyList(),
withHidden = false,
excludeNonMusic = false,
intelligentSorting = true,
separators = "",
coverMode = "AS_IS",
)
}
@Test
fun document_roundTrip_preservesCompleteGraphAndLivePlaylist() {
val storedCoverDirectory =
Files.createTempDirectory("auxio-document-cover").toFile().apply { deleteOnExit() }
val context = RuntimeEnvironment.getApplication()
val cover =
requireNotNull(
LibrarySnapshotCovers.restore("mcs:shared.webp", storedCoverDirectory, context)
)
val first =
preSong(61, "First", albumName = "Shared album", artistName = "Shared artist", genreName = "Shared genre", cover = cover)
val second =
preSong(
62,
"Second",
v400Uid = songUid(162),
albumName = "Shared album",
artistName = "Shared artist",
genreName = "Shared genre",
cover = cover,
)
val third = preSong(63, "Third", albumName = "Other album", artistName = "Other artist", genreName = "Other genre")
val missing = songUid(999)
val handle = TestPlaylistHandle(playlistUid(71))
val file =
PlaylistFile(
"Bangers",
listOf(
SongPointer.UID(third.v363Uid),
SongPointer.UID(first.v400Uid),
SongPointer.UID(missing),
SongPointer.UID(second.v363Uid),
SongPointer.UID(first.v363Uid),
),
handle,
)
val storedPlaylists = mockk<StoredPlaylists>()
coEvery { storedPlaylists.read() } returns listOf(file)
val playlistInterpreter = playlistInterpreter()
val original =
runBlocking {
LibrarySnapshotGraph.restore(
listOf(first, second, third),
storedPlaylists,
playlistInterpreter,
)
}
val output = ByteArrayOutputStream()
LibrarySnapshotDocument.write(output, listOf(first, second, third), TEST_FINGERPRINT)
val restored =
runBlocking {
LibrarySnapshotDocument.read(
ByteArrayInputStream(output.toByteArray()),
TEST_FINGERPRINT,
storedCoverDirectory,
context,
storedPlaylists,
playlistInterpreter,
)
}
val restoredSongs = restored.songs.associateBy { it.uid }
assertEquals(original.songs, restored.songs)
assertEquals(original.albums, restored.albums)
assertEquals(original.artists, restored.artists)
assertEquals(original.genres, restored.genres)
assertEquals(original.playlists, restored.playlists)
assertEquals(2, restored.albums.size)
assertEquals(2, restored.artists.size)
assertEquals(2, restored.genres.size)
assertSame(restoredSongs[first.v363Uid], restored.playlists.single().songs[1])
assertSame(
restoredSongs[third.v363Uid],
restored.playlists.single().songs.first(),
)
}
@Test
fun document_invalidSongCounts_rejectBeforePayloadAllocation() {
val storedCoverDirectory =
Files.createTempDirectory("auxio-invalid-count").toFile().apply { deleteOnExit() }
for (count in listOf(-1, 100_001)) {
val output = ByteArrayOutputStream()
LibrarySnapshotCodec.writeHeader(output)
LibrarySnapshotFingerprintCodec.write(output, TEST_FINGERPRINT)
LibrarySnapshotCodec.writeInt(output, count)
val error =
assertThrows(IOException::class.java) {
readDocument(
ByteArrayInputStream(output.toByteArray()),
storedCoverDirectory,
mockk<StoredPlaylists>(),
mockk<PlaylistInterpreter>(),
)
}
assertEquals("Invalid snapshot collection count: $count", error.message)
}
}
@Test
fun document_corruptionTrailingDataAndTruncation_failBeforeGraphConstruction() {
val storedCoverDirectory =
Files.createTempDirectory("auxio-integrity").toFile().apply { deleteOnExit() }
val song = preSong(81, "Integrity")
val storedPlaylists = mockk<StoredPlaylists>()
coEvery { storedPlaylists.read() } returns emptyList()
val output = ByteArrayOutputStream()
LibrarySnapshotDocument.write(output, listOf(song), TEST_FINGERPRINT)
val bytes = output.toByteArray()
val restored =
readDocument(
ByteArrayInputStream(bytes),
storedCoverDirectory,
storedPlaylists,
playlistInterpreter(),
)
assertEquals(1, restored.songs.size)
val corrupted = bytes.copyOf()
val corruptedIndex = corrupted.lastIndex - 8
corrupted[corruptedIndex] = (corrupted[corruptedIndex].toInt() xor 1).toByte()
val checksumError =
assertThrows(IOException::class.java) {
readDocument(
ByteArrayInputStream(corrupted),
storedCoverDirectory,
storedPlaylists,
playlistInterpreter(),
)
}
assertEquals("Snapshot checksum mismatch", checksumError.message)
val trailingError =
assertThrows(IOException::class.java) {
readDocument(
ByteArrayInputStream(bytes + byteArrayOf(0)),
storedCoverDirectory,
storedPlaylists,
playlistInterpreter(),
)
}
assertEquals("Trailing snapshot data", trailingError.message)
assertThrows(EOFException::class.java) {
readDocument(
ByteArrayInputStream(bytes.copyOf(bytes.size - 9)),
storedCoverDirectory,
storedPlaylists,
playlistInterpreter(),
)
}
assertThrows(EOFException::class.java) {
readDocument(
ByteArrayInputStream(bytes.copyOf(bytes.size - 1)),
storedCoverDirectory,
storedPlaylists,
playlistInterpreter(),
)
}
coVerify(exactly = 1) { storedPlaylists.read() }
}
private fun readDocument(
input: InputStream,
storedCoverDirectory: java.io.File,
storedPlaylists: StoredPlaylists,
playlistInterpreter: PlaylistInterpreter,
) = runBlocking {
LibrarySnapshotDocument.read(
input,
TEST_FINGERPRINT,
storedCoverDirectory,
RuntimeEnvironment.getApplication(),
storedPlaylists,
playlistInterpreter,
)
}
private fun playlistInterpreter(): PlaylistInterpreter {
val interpreter = mockk<PlaylistInterpreter>()
every { interpreter.interpret(any<PlaylistFile>()) } answers {
val file = firstArg<PlaylistFile>()
PrePlaylist(
Naming.simple().name(file.name, null),
file.name,
file.handle,
file.songPointers,
)
}
return interpreter
}
private fun preSong(
suffix: Int,
name: String,
v400Uid: Music.UID = songUid(suffix),
v401Uid: Music.UID = songUid(suffix),
albumName: String = "Album",
artistName: String = "Artist",
genreName: String = "Genre",
cover: org.oxycblt.musikr.covers.Cover? = null,
): PreSong {
val artist = PreArtist(null, Naming.simple().name(artistName, null), artistName)
return PreSong(
v363Uid = songUid(suffix),
v400Uid = v400Uid,
v401Uid = v401Uid,
musicBrainzId = null,
name = Naming.simple().name(name, null),
rawName = name,
track = null,
disc = null,
date = null,
uri = Uri.parse("content://snapshot/${songUid(suffix)}"),
path =
Path(
InternalVolumeValue(
null,
Components.parseUnix("/storage/emulated/0"),
"Internal shared storage",
),
Components.parseUnix("Download/$name.mp3"),
),
format = Format.MPEG3,
size = 1_024L,
durationMs = 60_000L,
bitrateKbps = 128,
sampleRateHz = 44_100,
replayGainAdjustment = ReplayGainAdjustment(null, null),
modifiedMs = 100L,
addedMs = 200L,
cover = cover,
preAlbum =
PreAlbum(
null,
Naming.simple().name(albumName, null),
albumName,
ReleaseType.Album(null),
PreArtistsFrom.Album(listOf(artist)),
),
preArtists = listOf(artist),
preGenres = listOf(PreGenre(Naming.simple().name(genreName, null), genreName)),
)
}
private fun songUid(suffix: Int, format: Char = 'a') =
requireNotNull(
Music.UID.fromString("u${format}s00000000-0000-4000-8000-${suffix.toString().padStart(12, '0')}")
)
private fun playlistUid(suffix: Int) =
requireNotNull(
Music.UID.fromString("uap00000000-0000-4000-8000-${suffix.toString().padStart(12, '0')}")
)
private class TestPlaylistHandle(override val uid: Music.UID) : PlaylistHandle {
override suspend fun rename(name: String) {}
override suspend fun add(songs: List<Song>) {}
override suspend fun rewrite(songs: List<Song>) {}
override suspend fun delete() {}
}
}
@@ -0,0 +1,65 @@
/*
* Copyright (c) 2026 Auxio Project
* LibrarySnapshotFileCodecTest.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.musikr.snapshot
import android.net.Uri
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.oxycblt.musikr.fs.Components
import org.oxycblt.musikr.fs.Format
import org.oxycblt.musikr.fs.Path
import org.oxycblt.musikr.fs.path.ExternalVolumeValue
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [30])
class LibrarySnapshotFileCodecTest {
@Test
fun fileProperties_roundTrip_preservesIdentitySizeAndTimestamps() {
val value =
LibrarySnapshotCodec.FileProperties(
uri = Uri.parse("content://media/7AFE-060A/audio/media/42"),
path =
Path(
ExternalVolumeValue(
"7AFE-060A",
"7afe-060a",
Components.parseUnix("/storage/7AFE-060A"),
"SD card",
),
Components.parseUnix("Development/Music/Library/song.ogg"),
),
format = Format.Ogg(Format.Opus),
size = 17_130_325L,
modifiedMs = 1_794_589_521_000L,
addedMs = 1_794_619_280_000L,
)
val output = ByteArrayOutputStream()
LibrarySnapshotCodec.writeFileProperties(output, value)
val decoded =
LibrarySnapshotCodec.readFileProperties(ByteArrayInputStream(output.toByteArray()))
assertEquals(value, decoded)
}
}
@@ -0,0 +1,178 @@
/*
* Copyright (c) 2026 Auxio Project
* LibrarySnapshotFingerprintTest.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.musikr.snapshot
import io.mockk.coEvery
import io.mockk.mockk
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.nio.file.Files
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.oxycblt.musikr.playlist.db.StoredPlaylists
import org.oxycblt.musikr.playlist.interpret.PlaylistInterpreter
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [30])
class LibrarySnapshotFingerprintTest {
@Test
fun matchingFingerprint_documentRestoresSuccessfully() {
val directory = Files.createTempDirectory("auxio-fingerprint-match").toFile().apply { deleteOnExit() }
val fingerprint = fingerprint()
val output = ByteArrayOutputStream()
LibrarySnapshotDocument.write(output, emptyList(), fingerprint)
val restored = readDocument(output.toByteArray(), fingerprint, directory)
assertTrue(restored.empty())
}
@Test
fun sourceModeOrRootChange_isRejectedAsFingerprintMismatch() {
val directory = Files.createTempDirectory("auxio-fingerprint-source").toFile().apply { deleteOnExit() }
val stored = fingerprint()
val output = ByteArrayOutputStream()
LibrarySnapshotDocument.write(output, emptyList(), stored)
val bytes = output.toByteArray()
val changedConfigurations =
listOf(
stored.copy(sourceMode = "MEDIA_STORE"),
stored.copy(sourceRoots = listOf("content://tree/Other")),
stored.copy(excludedRoots = listOf("content://tree/Development/Music/Other")),
)
for (expected in changedConfigurations) {
val error =
assertThrows(IOException::class.java) {
readDocument(bytes, expected, directory)
}
assertEquals("Snapshot fingerprint mismatch", error.message)
}
}
@Test
fun sortingOrSeparatorChange_isRejectedAsFingerprintMismatch() {
val directory = Files.createTempDirectory("auxio-fingerprint-names").toFile().apply { deleteOnExit() }
val stored = fingerprint()
val output = ByteArrayOutputStream()
LibrarySnapshotDocument.write(output, emptyList(), stored)
val bytes = output.toByteArray()
val changedConfigurations =
listOf(
stored.copy(intelligentSorting = false),
stored.copy(separators = ";&"),
)
for (expected in changedConfigurations) {
val error =
assertThrows(IOException::class.java) {
readDocument(bytes, expected, directory)
}
assertEquals("Snapshot fingerprint mismatch", error.message)
}
}
@Test
fun coverModeChange_isRejectedAsFingerprintMismatch() {
val directory = Files.createTempDirectory("auxio-fingerprint-covers").toFile().apply { deleteOnExit() }
val stored = fingerprint()
val output = ByteArrayOutputStream()
LibrarySnapshotDocument.write(output, emptyList(), stored)
val bytes = output.toByteArray()
val changedModes = listOf("OFF", "SAVE_SPACE", "HIGH_QUALITY", "AS_IS")
for (mode in changedModes) {
val error =
assertThrows(IOException::class.java) {
readDocument(bytes, stored.copy(coverMode = mode), directory)
}
assertEquals("Snapshot fingerprint mismatch", error.message)
}
}
@Test
fun mismatchedFingerprint_storeFallsBackAndPreservesUnrelatedCache() = runBlocking {
val root = Files.createTempDirectory("auxio-fingerprint-store").toFile().apply { deleteOnExit() }
val directory = File(root, "snapshots")
val cache = File(root, "tag-cache.db").apply { writeText("preserve-tags") }
val stored = fingerprint()
val store = LibrarySnapshotStore(directory)
store.replace(
write = { LibrarySnapshotDocument.write(it, emptyList(), stored) },
verify = { readStream(it, stored, directory) },
)
val invalid =
store.load {
readStream(it, stored.copy(sourceMode = "MEDIA_STORE"), directory)
}
val valid = store.load { readStream(it, stored, directory) }
assertNull(invalid)
assertEquals("preserve-tags", cache.readText())
assertTrue(valid?.empty() == true)
assertEquals("preserve-tags", cache.readText())
}
private fun readDocument(
bytes: ByteArray,
expectedFingerprint: LibrarySnapshotFingerprint,
directory: File,
) = readStream(ByteArrayInputStream(bytes), expectedFingerprint, directory)
private fun readStream(
input: InputStream,
expectedFingerprint: LibrarySnapshotFingerprint,
directory: File,
) = runBlocking {
val storedPlaylists = mockk<StoredPlaylists>()
coEvery { storedPlaylists.read() } returns emptyList()
LibrarySnapshotDocument.read(
input,
expectedFingerprint,
directory,
RuntimeEnvironment.getApplication(),
storedPlaylists,
mockk<PlaylistInterpreter>(),
)
}
private fun fingerprint() =
LibrarySnapshotFingerprint(
sourceMode = "SAF",
sourceRoots = listOf("content://tree/Development/Music"),
excludedRoots = listOf("content://tree/Development/Music/Excluded"),
withHidden = true,
excludeNonMusic = false,
intelligentSorting = true,
separators = ",;",
coverMode = "BALANCED",
)
}
@@ -0,0 +1,58 @@
/*
* Copyright (c) 2026 Auxio Project
* LibrarySnapshotFormatCodecTest.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.musikr.snapshot
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.oxycblt.musikr.fs.Format
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [30])
class LibrarySnapshotFormatCodecTest {
@Test
fun format_roundTrip_preservesEveryVariant() {
val values =
listOf(
Format.MPEG3,
Format.MPEG4(Format.AAC),
Format.MPEG4(null),
Format.AAC,
Format.ALAC,
Format.Ogg(Format.Vorbis),
Format.Ogg(null),
Format.Opus,
Format.Vorbis,
Format.FLAC,
Format.Wav,
Format.Unknown("audio/x-custom"),
)
val output = ByteArrayOutputStream()
values.forEach { LibrarySnapshotCodec.writeFormat(output, it) }
val input = ByteArrayInputStream(output.toByteArray())
val decoded = values.map { LibrarySnapshotCodec.readFormat(input) }
assertEquals(values, decoded)
}
}
@@ -0,0 +1,277 @@
/*
* Copyright (c) 2026 Auxio Project
* LibrarySnapshotGraphTest.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.musikr.snapshot
import android.net.Uri
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import java.nio.file.Files
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Assert.assertSame
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.oxycblt.musikr.Music
import org.oxycblt.musikr.covers.Cover
import org.oxycblt.musikr.fs.Components
import org.oxycblt.musikr.fs.Format
import org.oxycblt.musikr.fs.Path
import org.oxycblt.musikr.fs.path.InternalVolumeValue
import org.oxycblt.musikr.playlist.PlaylistHandle
import org.oxycblt.musikr.playlist.db.StoredPlaylists
import org.oxycblt.musikr.playlist.interpret.PlaylistInterpreter
import org.oxycblt.musikr.playlist.interpret.PostPlaylist
import org.oxycblt.musikr.tag.Name
import org.oxycblt.musikr.tag.ReleaseType
import org.oxycblt.musikr.tag.ReplayGainAdjustment
import org.oxycblt.musikr.tag.interpret.Naming
import org.oxycblt.musikr.tag.interpret.PreAlbum
import org.oxycblt.musikr.tag.interpret.PreArtist
import org.oxycblt.musikr.tag.interpret.PreArtistsFrom
import org.oxycblt.musikr.tag.interpret.PreGenre
import org.oxycblt.musikr.tag.interpret.PreSong
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [30])
class LibrarySnapshotGraphTest {
@Test
fun restore_sharedParentInputs_produceSingleSharedParentObjects() {
val first = preSong("uas00000000-0000-4000-8000-000000000001", "First")
val second = preSong("uas00000000-0000-4000-8000-000000000002", "Second")
val library =
restoreSongs(
listOf(first, second),
mockk<StoredPlaylists>(),
mockk<PlaylistInterpreter>(),
)
val songs = library.songs.associateBy { it.uid }
val firstSong = requireNotNull(songs[first.v363Uid])
val secondSong = requireNotNull(songs[second.v363Uid])
val album = library.albums.single()
val artist = library.artists.single()
val genre = library.genres.single()
assertEquals(2, library.songs.size)
assertSame(album, firstSong.album)
assertSame(album, secondSong.album)
assertSame(artist, firstSong.artists.single())
assertSame(artist, secondSong.artists.single())
assertSame(genre, firstSong.genres.single())
assertSame(genre, secondSong.genres.single())
assertSame(artist, album.artists.single())
assertSame(album, artist.explicitAlbums.single())
assertSame(genre, artist.genres.single())
}
@Test
fun restore_duplicateCurrentUid_keepsFirstRecordWithoutAdditionalParents() {
val uid = "uas00000000-0000-4000-8000-000000000003"
val first = preSong(uid, "First")
val duplicate =
preSong(
uid,
"Replacement",
albumName = "Other album",
artistName = "Other artist",
genreName = "Other genre",
)
val library =
restoreSongs(
listOf(first, duplicate),
mockk<StoredPlaylists>(),
mockk<PlaylistInterpreter>(),
)
val song = library.songs.single()
assertEquals(first.v363Uid, song.uid)
assertEquals("First", song.name.raw)
assertEquals("Album", (song.album.name as Name.Known).raw)
assertEquals("Artist", (song.artists.single().name as Name.Known).raw)
assertEquals("Genre", (song.genres.single().name as Name.Known).raw)
assertEquals(1, library.albums.size)
assertEquals(1, library.artists.size)
assertEquals(1, library.genres.size)
}
@Test
fun restore_findSong_supportsCurrentAndBothCompatibilityUids() {
val value =
preSong(
uid = "uas00000000-0000-4000-8000-000000000004",
name = "Tracked",
v400Uid = "uas00000000-0000-4000-8000-000000000104",
v401Uid = "ums00000000-0000-4000-8000-000000000204",
)
val library =
restoreSongs(
listOf(value),
mockk<StoredPlaylists>(),
mockk<PlaylistInterpreter>(),
)
val song = library.songs.single()
assertSame(song, library.findSong(value.v363Uid))
assertSame(song, library.findSong(value.v400Uid))
assertSame(song, library.findSong(value.v401Uid))
}
@Test
fun restore_coverReferences_preserveSongAndParentImageIdentity() {
val storedCoverDirectory =
Files.createTempDirectory("auxio-graph-cover").toFile().apply { deleteOnExit() }
val cover =
requireNotNull(
LibrarySnapshotCovers.restore(
"mcs:shared.webp",
storedCoverDirectory,
RuntimeEnvironment.getApplication(),
)
)
val library =
restoreSongs(
listOf(
preSong(
"uas00000000-0000-4000-8000-000000000005",
"Illustrated",
cover = cover,
)
),
mockk<StoredPlaylists>(),
mockk<PlaylistInterpreter>(),
)
val song = library.songs.single()
val albumCovers = song.album.covers.covers
val artistCovers = song.artists.single().covers.covers
val genreCovers = song.genres.single().covers.covers
assertSame(cover, song.cover)
assertEquals(1, albumCovers.size)
assertEquals(1, artistCovers.size)
assertEquals(1, genreCovers.size)
assertSame(cover, albumCovers.single())
assertSame(cover, artistCovers.single())
assertSame(cover, genreCovers.single())
}
@Test
fun restoredMutableLibrary_createPlaylist_usesRetainedLiveDependencies() {
val storedPlaylists = mockk<StoredPlaylists>()
val playlistInterpreter = mockk<PlaylistInterpreter>()
val handle = mockk<PlaylistHandle>()
val playlistUid =
requireNotNull(Music.UID.fromString("uap00000000-0000-4000-8000-000000000006"))
every { handle.uid } returns playlistUid
val library =
restoreSongs(
listOf(preSong("uas00000000-0000-4000-8000-000000000006", "Mutable")),
storedPlaylists,
playlistInterpreter,
)
val song = library.songs.single()
coEvery { storedPlaylists.new("Created", listOf(song)) } returns handle
every { playlistInterpreter.interpret("Created", handle) } returns
PostPlaylist(Naming.simple().name("Created", null), "Created", handle)
val updated = runBlocking { library.createPlaylist("Created", listOf(song)) }
val created = updated.playlists.single()
assertTrue(library.playlists.isEmpty())
assertEquals(playlistUid, created.uid)
assertEquals("Created", created.name.raw)
assertSame(song, created.songs.single())
assertSame(created, updated.findPlaylist(playlistUid))
assertSame(created, updated.findPlaylistByName("Created"))
coVerify(exactly = 1) { storedPlaylists.new("Created", listOf(song)) }
verify(exactly = 1) { playlistInterpreter.interpret("Created", handle) }
}
private fun restoreSongs(
songs: List<PreSong>,
storedPlaylists: StoredPlaylists,
playlistInterpreter: PlaylistInterpreter,
) = runBlocking {
coEvery { storedPlaylists.read() } returns emptyList()
LibrarySnapshotGraph.restore(songs, storedPlaylists, playlistInterpreter)
}
private fun preSong(
uid: String,
name: String,
v400Uid: String = uid,
v401Uid: String = uid,
albumName: String = "Album",
artistName: String = "Artist",
genreName: String = "Genre",
cover: Cover? = null,
): PreSong {
val artist =
PreArtist(null, Naming.simple().name(artistName, null), artistName)
return PreSong(
v363Uid = requireNotNull(Music.UID.fromString(uid)),
v400Uid = requireNotNull(Music.UID.fromString(v400Uid)),
v401Uid = requireNotNull(Music.UID.fromString(v401Uid)),
musicBrainzId = null,
name = Naming.simple().name(name, null),
rawName = name,
track = null,
disc = null,
date = null,
uri = Uri.parse("content://snapshot/$uid"),
path =
Path(
InternalVolumeValue(
null,
Components.parseUnix("/storage/emulated/0"),
"Internal shared storage",
),
Components.parseUnix("Download/$name.mp3"),
),
format = Format.MPEG3,
size = 1_024L,
durationMs = 60_000L,
bitrateKbps = 128,
sampleRateHz = 44_100,
replayGainAdjustment = ReplayGainAdjustment(null, null),
modifiedMs = 100L,
addedMs = 200L,
cover = cover,
preAlbum =
PreAlbum(
musicBrainzId = null,
name = Naming.simple().name(albumName, null),
rawName = albumName,
releaseType = ReleaseType.Album(null),
preArtists = PreArtistsFrom.Album(listOf(artist)),
),
preArtists = listOf(artist),
preGenres = listOf(PreGenre(Naming.simple().name(genreName, null), genreName)),
)
}
}
@@ -0,0 +1,168 @@
/*
* Copyright (c) 2026 Auxio Project
* LibrarySnapshotNameCodecTest.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.musikr.snapshot
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.DataOutputStream
import java.io.IOException
import org.junit.Assert.assertEquals
import org.junit.Assert.assertThrows
import org.junit.Test
import org.oxycblt.musikr.tag.Name
import org.oxycblt.musikr.tag.Placeholder
import org.oxycblt.musikr.tag.Token
import org.oxycblt.musikr.tag.interpret.IntelligentNaming
import org.oxycblt.musikr.tag.interpret.Naming
class LibrarySnapshotNameCodecTest {
@Test
fun unknownName_roundTrip_preservesEveryPlaceholder() {
val values =
listOf(
Name.Unknown(Placeholder.ALBUM),
Name.Unknown(Placeholder.ARTIST),
Name.Unknown(Placeholder.GENRE),
)
val output = ByteArrayOutputStream()
values.forEach { LibrarySnapshotCodec.writeName(output, it) }
val input = ByteArrayInputStream(output.toByteArray())
val decoded = values.map { LibrarySnapshotCodec.readName(input) }
assertEquals(values, decoded)
}
@Test
fun knownName_roundTrip_preservesRawSortAndTokens() {
val value = Naming.simple().name("The Smile", "Smile")
val output = ByteArrayOutputStream()
LibrarySnapshotCodec.writeName(output, value)
val decoded =
LibrarySnapshotCodec.readName(ByteArrayInputStream(output.toByteArray())) as Name.Known
assertEquals(value, decoded)
assertEquals("The Smile", decoded.raw)
assertEquals("Smile", decoded.sort)
assertEquals(listOf("Smile"), decoded.tokens.map { it.value })
}
@Test
fun knownName_numericAndPunctuationTokens_preserveParsedValuesAndTypes() {
val value =
IntelligentNaming(transliteratorFactory = { { input -> input } }).name("15-9", null)
val output = ByteArrayOutputStream()
LibrarySnapshotCodec.writeName(output, value)
val decoded =
LibrarySnapshotCodec.readName(ByteArrayInputStream(output.toByteArray())) as Name.Known
assertEquals(value, decoded)
assertEquals("15-9", decoded.raw)
assertEquals(listOf("15", " ", "9"), decoded.tokens.map { it.value })
assertEquals(
listOf(Token.Type.NUMERIC, Token.Type.LEXICOGRAPHIC, Token.Type.NUMERIC),
decoded.tokens.map { it.type },
)
}
@Test
fun knownName_nonLatinAndLeadingZeroText_preserveRawAndStoredTokens() {
val value =
IntelligentNaming(transliteratorFactory = { { input -> input } })
.name("初音 0032", null)
val output = ByteArrayOutputStream()
LibrarySnapshotCodec.writeName(output, value)
val decoded =
LibrarySnapshotCodec.readName(ByteArrayInputStream(output.toByteArray())) as Name.Known
assertEquals(value, decoded)
assertEquals("初音 0032", decoded.raw)
assertEquals(listOf("初音", "32"), decoded.tokens.map { it.value })
assertEquals(
listOf(Token.Type.LEXICOGRAPHIC, Token.Type.NUMERIC),
decoded.tokens.map { it.type },
)
}
@Test
fun knownName_restoration_reusesStoredTransliterations() {
var transliterations = 0
val value =
IntelligentNaming(
transliteratorFactory = {
{
transliterations += 1
"Hatsune Miku"
}
}
)
.name("初音ミク", null)
assertEquals(1, transliterations)
val output = ByteArrayOutputStream()
LibrarySnapshotCodec.writeName(output, value)
val decoded =
LibrarySnapshotCodec.readName(ByteArrayInputStream(output.toByteArray())) as Name.Known
assertEquals(value, decoded)
assertEquals("Hatsune Miku", decoded.tokens.single().value)
assertEquals(1, transliterations)
}
@Test
fun name_malformedNameAndTokenData_throwIOException() {
val invalidName = ByteArrayOutputStream()
LibrarySnapshotCodec.writeInt(invalidName, 99)
assertThrows(IOException::class.java) {
LibrarySnapshotCodec.readName(ByteArrayInputStream(invalidName.toByteArray()))
}
val invalidPlaceholder = ByteArrayOutputStream()
LibrarySnapshotCodec.writeInt(invalidPlaceholder, 0)
LibrarySnapshotCodec.writeInt(invalidPlaceholder, 99)
assertThrows(IOException::class.java) {
LibrarySnapshotCodec.readName(ByteArrayInputStream(invalidPlaceholder.toByteArray()))
}
for (count in listOf(-1, 10_001)) {
val invalidCount = ByteArrayOutputStream()
LibrarySnapshotCodec.writeInt(invalidCount, 1)
LibrarySnapshotCodec.writeString(invalidCount, "raw")
LibrarySnapshotCodec.writeNullableString(invalidCount, null)
DataOutputStream(invalidCount).writeInt(count)
assertThrows(IOException::class.java) {
LibrarySnapshotCodec.readName(ByteArrayInputStream(invalidCount.toByteArray()))
}
}
val invalidToken = ByteArrayOutputStream()
LibrarySnapshotCodec.writeInt(invalidToken, 1)
LibrarySnapshotCodec.writeString(invalidToken, "raw")
LibrarySnapshotCodec.writeNullableString(invalidToken, null)
LibrarySnapshotCodec.writeCount(invalidToken, 1, maximum = 10_000)
LibrarySnapshotCodec.writeString(invalidToken, "token")
LibrarySnapshotCodec.writeInt(invalidToken, 99)
assertThrows(IOException::class.java) {
LibrarySnapshotCodec.readName(ByteArrayInputStream(invalidToken.toByteArray()))
}
}
}
@@ -0,0 +1,326 @@
/*
* Copyright (c) 2026 Auxio Project
* LibrarySnapshotPlaylistRestoreTest.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.musikr.snapshot
import android.net.Uri
import io.mockk.Runs
import io.mockk.coEvery
import io.mockk.every
import io.mockk.just
import io.mockk.mockk
import io.mockk.slot
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Assert.assertSame
import org.junit.Test
import org.junit.runner.RunWith
import org.oxycblt.musikr.Music
import org.oxycblt.musikr.Song
import org.oxycblt.musikr.fs.Components
import org.oxycblt.musikr.fs.Format
import org.oxycblt.musikr.fs.Path
import org.oxycblt.musikr.fs.path.InternalVolumeValue
import org.oxycblt.musikr.model.PlaylistImpl
import org.oxycblt.musikr.playlist.PlaylistFile
import org.oxycblt.musikr.playlist.PlaylistHandle
import org.oxycblt.musikr.playlist.PlaylistReconciler
import org.oxycblt.musikr.playlist.SongPointer
import org.oxycblt.musikr.playlist.db.PlaylistDao
import org.oxycblt.musikr.playlist.db.PlaylistInfo
import org.oxycblt.musikr.playlist.db.StoredPlaylistHandle
import org.oxycblt.musikr.playlist.db.StoredPlaylists
import org.oxycblt.musikr.playlist.interpret.PlaylistInterpreter
import org.oxycblt.musikr.playlist.interpret.PostPlaylist
import org.oxycblt.musikr.playlist.interpret.PrePlaylist
import org.oxycblt.musikr.tag.ReleaseType
import org.oxycblt.musikr.tag.ReplayGainAdjustment
import org.oxycblt.musikr.tag.interpret.Naming
import org.oxycblt.musikr.tag.interpret.PreAlbum
import org.oxycblt.musikr.tag.interpret.PreArtist
import org.oxycblt.musikr.tag.interpret.PreArtistsFrom
import org.oxycblt.musikr.tag.interpret.PreGenre
import org.oxycblt.musikr.tag.interpret.PreSong
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [30])
class LibrarySnapshotPlaylistRestoreTest {
@Test
fun restore_preservesLivePlaylistOrderAndRestoredSongLinks() {
val first = preSong("uas00000000-0000-4000-8000-000000000011", "First")
val second = preSong("uas00000000-0000-4000-8000-000000000012", "Second")
val third = preSong("uas00000000-0000-4000-8000-000000000013", "Third")
val handle = TestPlaylistHandle(playlistUid(11))
val storedPlaylists =
InMemoryStoredPlaylists(
listOf(playlistFile("Ordered", listOf(third, first, second), handle))
)
val library = restore(listOf(first, second, third), storedPlaylists)
val playlist = library.playlists.single()
val expected = listOf(third.v363Uid, first.v363Uid, second.v363Uid)
assertEquals(expected, playlist.songs.map { it.uid })
playlist.songs.zip(expected).forEach { (song, uid) ->
assertSame(library.findSong(uid), song)
}
}
@Test
fun restore_duplicatePointers_preserveEvery_PositionAndSongIdentity() {
val first = preSong("uas00000000-0000-4000-8000-000000000021", "First")
val second = preSong("uas00000000-0000-4000-8000-000000000022", "Second")
val handle = TestPlaylistHandle(playlistUid(22))
val storedPlaylists =
InMemoryStoredPlaylists(
listOf(playlistFile("Duplicates", listOf(first, first, second, first), handle))
)
val library = restore(listOf(first, second), storedPlaylists)
val playlist = library.playlists.single()
val restoredFirst = requireNotNull(library.findSong(first.v363Uid))
assertEquals(2, library.songs.size)
assertEquals(4, playlist.songs.size)
assertEquals(
listOf(first.v363Uid, first.v363Uid, second.v363Uid, first.v363Uid),
playlist.songs.map { it.uid },
)
assertSame(restoredFirst, playlist.songs[0])
assertSame(restoredFirst, playlist.songs[1])
assertSame(restoredFirst, playlist.songs[3])
assertSame(library.findSong(second.v363Uid), playlist.songs[2])
}
@Test
fun restore_liveHandle_andRenamePreserveTrackedSourceMetadata() {
val uid = playlistUid(33)
val sourceUri = "content://tree/Playlists/Bangers.m3u"
val dao = mockk<PlaylistDao>()
val updatedInfo = slot<PlaylistInfo>()
coEvery { dao.replacePlaylistInfo(capture(updatedInfo)) } just Runs
val handle =
StoredPlaylistHandle(PlaylistInfo(uid, "Tracked", sourceUri, 42L), dao)
val song = preSong("uas00000000-0000-4000-8000-000000000033", "Tracked song")
val storedPlaylists =
InMemoryStoredPlaylists(listOf(playlistFile("Tracked", listOf(song), handle)))
val library = restore(listOf(song), storedPlaylists)
val playlist = library.playlists.single()
val restoredHandle = (playlist as PlaylistImpl).core.prePlaylist.handle
assertSame(handle, restoredHandle)
val updated = runBlocking { library.renamePlaylist(playlist, "Renamed") }
val updatedHandle = (updated.playlists.single() as PlaylistImpl).core.prePlaylist.handle
assertSame(handle, updatedHandle)
assertEquals(uid, updatedInfo.captured.playlistUid)
assertEquals("Renamed", updatedInfo.captured.name)
assertEquals(sourceUri, updatedInfo.captured.sourceUri)
assertEquals(42L, updatedInfo.captured.sourceSignature)
}
@Test
fun restore_afterStoredPlaylistEdit_usesCurrentDatabaseContent() {
val first = preSong("uas00000000-0000-4000-8000-000000000041", "First")
val second = preSong("uas00000000-0000-4000-8000-000000000042", "Second")
val handle = TestPlaylistHandle(playlistUid(44))
val capturedSongs = listOf(first, second)
val storedPlaylists =
InMemoryStoredPlaylists(
listOf(playlistFile("Bangers", listOf(first, second), handle))
)
val firstLibrary = restore(capturedSongs, storedPlaylists)
storedPlaylists.files = listOf(playlistFile("Edited", listOf(second), handle))
val secondLibrary = restore(capturedSongs, storedPlaylists)
val original = firstLibrary.playlists.single()
val edited = secondLibrary.playlists.single()
assertEquals("Bangers", original.name.raw)
assertEquals(listOf(first.v363Uid, second.v363Uid), original.songs.map { it.uid })
assertEquals("Edited", edited.name.raw)
assertEquals(listOf(second.v363Uid), edited.songs.map { it.uid })
assertSame(secondLibrary.findSong(second.v363Uid), edited.songs.single())
assertSame(handle, (edited as PlaylistImpl).core.prePlaylist.handle)
}
@Test
fun restore_compatibilityAndMissingPointers_resolveNormallyWithoutTruncation() {
val first = preSong("uas00000000-0000-4000-8000-000000000051", "First")
val second =
preSong(
"uas00000000-0000-4000-8000-000000000052",
"Second",
v400Uid = "uas00000000-0000-4000-8000-000000000152",
)
val third =
preSong(
"uas00000000-0000-4000-8000-000000000053",
"Third",
v401Uid = "ums00000000-0000-4000-8000-000000000253",
)
val missing =
requireNotNull(
Music.UID.fromString("uas00000000-0000-4000-8000-000000000999")
)
val file =
PlaylistFile(
"Pointers",
listOf(
SongPointer.UID(first.v363Uid),
SongPointer.UID(second.v400Uid),
SongPointer.UID(missing),
SongPointer.UID(third.v401Uid),
),
TestPlaylistHandle(playlistUid(55)),
)
val library =
restore(listOf(first, second, third), InMemoryStoredPlaylists(listOf(file)))
val playlist = library.playlists.single()
val expected = listOf(first, second, third)
assertEquals(expected.map { it.v363Uid }, playlist.songs.map { it.uid })
expected.zip(playlist.songs).forEach { (input, song) ->
assertSame(library.findSong(input.v363Uid), song)
}
}
private fun restore(
songs: List<PreSong>,
storedPlaylists: StoredPlaylists,
playlistInterpreter: PlaylistInterpreter = playlistInterpreter(),
) = runBlocking {
LibrarySnapshotGraph.restore(songs, storedPlaylists, playlistInterpreter)
}
private fun playlistInterpreter(): PlaylistInterpreter {
val interpreter = mockk<PlaylistInterpreter>()
every { interpreter.interpret(any<PlaylistFile>()) } answers {
val file = firstArg<PlaylistFile>()
PrePlaylist(
Naming.simple().name(file.name, null),
file.name,
file.handle,
file.songPointers,
)
}
every { interpreter.interpret(any<String>(), any<PlaylistHandle>()) } answers {
val name = firstArg<String>()
val handle = secondArg<PlaylistHandle>()
PostPlaylist(Naming.simple().name(name, null), name, handle)
}
return interpreter
}
private fun playlistFile(name: String, songs: List<PreSong>, handle: PlaylistHandle) =
PlaylistFile(name, songs.map { SongPointer.UID(it.v363Uid) }, handle)
private fun playlistUid(suffix: Int) =
requireNotNull(
Music.UID.fromString("uap00000000-0000-4000-8000-${suffix.toString().padStart(12, '0')}")
)
private fun preSong(
uid: String,
name: String,
v400Uid: String = uid,
v401Uid: String = uid,
): PreSong {
val artist = PreArtist(null, Naming.simple().name("Artist", null), "Artist")
return PreSong(
v363Uid = requireNotNull(Music.UID.fromString(uid)),
v400Uid = requireNotNull(Music.UID.fromString(v400Uid)),
v401Uid = requireNotNull(Music.UID.fromString(v401Uid)),
musicBrainzId = null,
name = Naming.simple().name(name, null),
rawName = name,
track = null,
disc = null,
date = null,
uri = Uri.parse("content://snapshot/$uid"),
path =
Path(
InternalVolumeValue(
null,
Components.parseUnix("/storage/emulated/0"),
"Internal shared storage",
),
Components.parseUnix("Download/$name.mp3"),
),
format = Format.MPEG3,
size = 1_024L,
durationMs = 60_000L,
bitrateKbps = 128,
sampleRateHz = 44_100,
replayGainAdjustment = ReplayGainAdjustment(null, null),
modifiedMs = 100L,
addedMs = 200L,
cover = null,
preAlbum =
PreAlbum(
null,
Naming.simple().name("Album", null),
"Album",
ReleaseType.Album(null),
PreArtistsFrom.Album(listOf(artist)),
),
preArtists = listOf(artist),
preGenres = listOf(PreGenre(Naming.simple().name("Genre", null), "Genre")),
)
}
private class TestPlaylistHandle(override val uid: Music.UID) : PlaylistHandle {
override suspend fun rename(name: String) {}
override suspend fun add(songs: List<Song>) {}
override suspend fun rewrite(songs: List<Song>) {}
override suspend fun delete() {}
}
private class InMemoryStoredPlaylists(
var files: List<PlaylistFile>,
var tracked: List<PlaylistReconciler.Tracked> = emptyList(),
) : StoredPlaylists() {
override suspend fun new(name: String, songs: List<Song>): PlaylistHandle =
error("Snapshot restoration must not create playlists")
override suspend fun newTracked(
name: String,
songUids: List<Music.UID>,
sourceUri: String,
sourceSignature: Long,
): PlaylistHandle = error("Snapshot restoration must not create playlists")
override suspend fun replaceTracked(
playlistUid: Music.UID,
name: String,
songUids: List<Music.UID>,
sourceSignature: Long,
) = error("Snapshot restoration must not replace playlists")
override suspend fun readTracked() = tracked
override suspend fun read() = files
}
}
@@ -0,0 +1,235 @@
/*
* Copyright (c) 2026 Auxio Project
* LibrarySnapshotSongCodecTest.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.musikr.snapshot
import android.net.Uri
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.nio.file.Files
import java.util.UUID
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.oxycblt.musikr.Music
import org.oxycblt.musikr.fs.Components
import org.oxycblt.musikr.fs.Format
import org.oxycblt.musikr.fs.Path
import org.oxycblt.musikr.fs.path.ExternalVolumeValue
import org.oxycblt.musikr.fs.path.InternalVolumeValue
import org.oxycblt.musikr.tag.Date
import org.oxycblt.musikr.tag.Disc
import org.oxycblt.musikr.tag.Name
import org.oxycblt.musikr.tag.Placeholder
import org.oxycblt.musikr.tag.ReleaseType
import org.oxycblt.musikr.tag.ReplayGainAdjustment
import org.oxycblt.musikr.tag.interpret.Naming
import org.oxycblt.musikr.tag.interpret.PreAlbum
import org.oxycblt.musikr.tag.interpret.PreArtist
import org.oxycblt.musikr.tag.interpret.PreArtistsFrom
import org.oxycblt.musikr.tag.interpret.PreGenre
import org.oxycblt.musikr.tag.interpret.PreSong
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [30])
class LibrarySnapshotSongCodecTest {
@Test
fun preSong_roundTrip_preservesEveryCapturedField() {
val storedCoverDirectory =
Files.createTempDirectory("auxio-song-cover").toFile().apply { deleteOnExit() }
val context = RuntimeEnvironment.getApplication()
val value =
PreSong(
v363Uid =
requireNotNull(
Music.UID.fromString("uas00112233-4455-6677-8899-aabbccddeeff")
),
v400Uid =
requireNotNull(
Music.UID.fromString("ums11111111-2222-4333-8444-555566667777")
),
v401Uid =
requireNotNull(
Music.UID.fromString("uas88888888-9999-4aaa-bbbb-ccccddddeeee")
),
musicBrainzId = UUID.fromString("01234567-89ab-4cde-8fab-0123456789ab"),
name = Naming.simple().name("15-9", "nine"),
rawName = "15-9",
track = 9,
disc = Disc(2, "Bonus 界"),
date = requireNotNull(Date.from("2016-08-16T00:01:02Z")),
uri =
Uri.parse(
"content://media/7AFE-060A/audio/media/42/Music/%E5%88%9D%E9%9F%B3.ogg"
),
path =
Path(
ExternalVolumeValue(
"7AFE-060A",
"7afe-060a",
Components.parseUnix("/storage/7AFE-060A"),
"SD card",
),
Components.parseUnix("Development/Music/Library/初音/15-9.ogg"),
),
format = Format.Ogg(Format.Opus),
size = 17_130_325L,
durationMs = 256_008L,
bitrateKbps = 256,
sampleRateHz = 48_000,
replayGainAdjustment = ReplayGainAdjustment(track = -6.5f, album = -9.0f),
modifiedMs = 1_794_589_521_000L,
addedMs = 1_794_619_280_000L,
cover =
requireNotNull(
LibrarySnapshotCovers.restore("mcs:cover.webp", storedCoverDirectory, context)
),
preAlbum =
PreAlbum(
musicBrainzId =
UUID.fromString("12345678-9abc-4def-8123-456789abcdef"),
name = Naming.simple().name("The Silent Force", "Silent Force"),
rawName = "The Silent Force",
releaseType = ReleaseType.Compilation(ReleaseType.Refinement.LIVE),
preArtists =
PreArtistsFrom.Individual(
listOf(
PreArtist(
UUID.fromString(
"abcdef01-2345-4678-9abc-def012345678"
),
Naming.simple().name("初音ミク", "Hatsune Miku"),
"初音ミク",
)
)
),
),
preArtists =
listOf(
PreArtist(
UUID.fromString("abcdef01-2345-4678-9abc-def012345678"),
Naming.simple().name("初音ミク", "Hatsune Miku"),
"初音ミク",
),
PreArtist(null, Naming.simple().name("Within Temptation", null), "Within Temptation"),
),
preGenres =
listOf(
PreGenre(Naming.simple().name("J-pop", null), "J-pop"),
PreGenre(Naming.simple().name("Symphonic 0032", null), "Symphonic 0032"),
),
)
val output = ByteArrayOutputStream()
LibrarySnapshotCodec.writePreSong(output, value)
val decoded =
LibrarySnapshotCodec.readPreSong(
ByteArrayInputStream(output.toByteArray()),
storedCoverDirectory,
context,
)
assertEquals(value, decoded)
assertEquals(value.disc?.name, decoded.disc?.name)
}
@Test
fun preSong_optionalAndCompatibilityFields_roundTripWithoutSubstitutingDefaults() {
val storedCoverDirectory =
Files.createTempDirectory("auxio-optional-song").toFile().apply { deleteOnExit() }
val context = RuntimeEnvironment.getApplication()
val unknownArtist = PreArtist(null, Name.Unknown(Placeholder.ARTIST), null)
val value =
PreSong(
v363Uid =
requireNotNull(
Music.UID.fromString("uas11111111-2222-4333-8444-555566667777")
),
v400Uid =
requireNotNull(
Music.UID.fromString("uas22222222-3333-4444-8555-666677778888")
),
v401Uid =
requireNotNull(
Music.UID.fromString("ums33333333-4444-4555-8666-777788889999")
),
musicBrainzId = null,
name = Naming.simple().name("Loose file", null),
rawName = "Loose file",
track = null,
disc = null,
date = null,
uri = Uri.parse("content://media/internal/audio/media/7"),
path =
Path(
InternalVolumeValue(
null,
Components.parseUnix("/storage/emulated/0"),
"Internal shared storage",
),
Components.parseUnix("Download/Loose file.mp3"),
),
format = Format.MPEG3,
size = 8_192L,
durationMs = 1_000L,
bitrateKbps = 128,
sampleRateHz = 44_100,
replayGainAdjustment = ReplayGainAdjustment(track = null, album = null),
modifiedMs = 0L,
addedMs = 1L,
cover = null,
preAlbum =
PreAlbum(
musicBrainzId = null,
name = Name.Unknown(Placeholder.ALBUM),
rawName = null,
releaseType = ReleaseType.Album(null),
preArtists = PreArtistsFrom.Album(listOf(unknownArtist)),
),
preArtists = listOf(unknownArtist),
preGenres = listOf(PreGenre(Name.Unknown(Placeholder.GENRE), null)),
)
val output = ByteArrayOutputStream()
LibrarySnapshotCodec.writePreSong(output, value)
val decoded =
LibrarySnapshotCodec.readPreSong(
ByteArrayInputStream(output.toByteArray()),
storedCoverDirectory,
context,
)
val decodedUids = listOf(decoded.v363Uid, decoded.v400Uid, decoded.v401Uid)
assertEquals(value, decoded)
assertEquals(listOf(value.v363Uid, value.v400Uid, value.v401Uid), decodedUids)
assertEquals(3, decodedUids.toSet().size)
assertNull(decoded.musicBrainzId)
assertNull(decoded.track)
assertNull(decoded.disc)
assertNull(decoded.date)
assertNull(decoded.cover)
assertNull(decoded.preAlbum.musicBrainzId)
assertNull(decoded.preAlbum.rawName)
assertTrue(decoded.preAlbum.preArtists is PreArtistsFrom.Album)
}
}
@@ -0,0 +1,172 @@
/*
* Copyright (c) 2026 Auxio Project
* LibrarySnapshotStoreTest.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.musikr.snapshot
import java.io.ByteArrayOutputStream
import java.io.EOFException
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.nio.file.AtomicMoveNotSupportedException
import java.nio.file.Files
import kotlin.coroutines.cancellation.CancellationException
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertThrows
import org.junit.Test
class LibrarySnapshotStoreTest {
@Test
fun load_missingSnapshot_returnsNullWithoutCreatingDirectory() = runBlocking {
val root = Files.createTempDirectory("auxio-store-missing").toFile().apply { deleteOnExit() }
val directory = File(root, "snapshots")
val store = LibrarySnapshotStore(directory)
val result = store.load<String> { error("Absent snapshot must not be decoded") }
assertNull(result)
assertFalse(directory.exists())
}
@Test
fun replace_validSnapshot_verifiesContentsAndCleansTemporaryFiles() = runBlocking {
val directory = Files.createTempDirectory("auxio-store-valid").toFile().apply { deleteOnExit() }
val store = LibrarySnapshotStore(directory)
store.replace(
write = { writeSnapshot(it, "first") },
verify = { assertEquals("first", readSnapshot(it)) },
)
assertEquals("first", store.load(::readSnapshot))
store.replace(
write = { writeSnapshot(it, "second") },
verify = { assertEquals("second", readSnapshot(it)) },
)
assertEquals("second", store.load(::readSnapshot))
assertEquals(listOf("library.snapshot"), directory.listFiles()!!.map { it.name })
}
@Test
fun load_corruptOrTruncatedSnapshot_fallsBackWithoutTouchingOtherFiles() = runBlocking {
val directory = Files.createTempDirectory("auxio-store-invalid").toFile().apply { deleteOnExit() }
val store = LibrarySnapshotStore(directory)
val snapshot = File(directory, "library.snapshot")
val unrelated = File(directory, "unrelated-cache")
unrelated.writeText("preserved")
val valid = ByteArrayOutputStream().also { writeSnapshot(it, "valid") }.toByteArray()
val invalidDocuments =
listOf(
"invalid-magic".toByteArray(),
valid.copyOf(valid.size - 2),
)
for (invalid in invalidDocuments) {
snapshot.writeBytes(invalid)
assertNull(store.load(::readSnapshot))
assertEquals("preserved", unrelated.readText())
}
}
@Test
fun replace_failedWriteVerificationCancellationOrMove_preservesPreviousAndCleansTemps() = runBlocking {
val directory = Files.createTempDirectory("auxio-store-failed").toFile().apply { deleteOnExit() }
val store = LibrarySnapshotStore(directory)
store.replace(
write = { writeSnapshot(it, "stable") },
verify = { assertEquals("stable", readSnapshot(it)) },
)
assertSuspendThrows<IllegalStateException> {
store.replace(
write = {
writeSnapshot(it, "write-failed")
throw IllegalStateException("Forced write failure")
},
verify = { error("Failed write must not be verified") },
)
}
assertEquals("stable", store.load(::readSnapshot))
assertSuspendThrows<CancellationException> {
store.replace(
write = {
writeSnapshot(it, "cancelled")
throw CancellationException("Forced cancellation")
},
verify = { error("Cancelled write must not be verified") },
)
}
assertEquals("stable", store.load(::readSnapshot))
val truncated = ByteArrayOutputStream()
LibrarySnapshotCodec.writeHeader(truncated)
LibrarySnapshotCodec.writeInt(truncated, 10)
truncated.write('v'.code)
assertSuspendThrows<EOFException> {
store.replace(
write = { it.write(truncated.toByteArray()) },
verify = { readSnapshot(it) },
)
}
assertEquals("stable", store.load(::readSnapshot))
val failedMoveStore =
LibrarySnapshotStore(directory) { source, target ->
throw AtomicMoveNotSupportedException(
source.toString(),
target.toString(),
"Forced move failure",
)
}
assertSuspendThrows<AtomicMoveNotSupportedException> {
failedMoveStore.replace(
write = { writeSnapshot(it, "move-failed") },
verify = { assertEquals("move-failed", readSnapshot(it)) },
)
}
assertEquals("stable", store.load(::readSnapshot))
assertEquals(listOf("library.snapshot"), directory.listFiles()!!.map { it.name })
}
private inline fun <reified T : Throwable> assertSuspendThrows(
noinline block: suspend () -> Unit
) {
org.junit.Assert.assertThrows(T::class.java) { runBlocking { block() } }
}
private fun writeSnapshot(output: OutputStream, value: String) {
LibrarySnapshotCodec.writeHeader(output)
LibrarySnapshotCodec.writeString(output, value)
}
private fun readSnapshot(input: InputStream): String {
LibrarySnapshotCodec.readHeader(input)
val value = LibrarySnapshotCodec.readString(input)
if (input.read() != -1) {
throw IOException("Trailing test data")
}
return value
}
}
@@ -0,0 +1,43 @@
/*
* Copyright (c) 2026 Auxio Project
* LibrarySnapshotUriCodecTest.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.musikr.snapshot
import android.net.Uri
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [30])
class LibrarySnapshotUriCodecTest {
@Test
fun uri_roundTrip_preservesCanonicalText() {
val uri = Uri.parse("content://org.oxycblt.auxio/Library/初音%20ミク.mp3")
val output = ByteArrayOutputStream()
LibrarySnapshotCodec.writeUri(output, uri)
val decoded = LibrarySnapshotCodec.readUri(ByteArrayInputStream(output.toByteArray()))
assertEquals(uri, decoded)
}
}
@@ -18,8 +18,10 @@
package org.oxycblt.musikr.tag.interpret package org.oxycblt.musikr.tag.interpret
import java.util.concurrent.atomic.AtomicInteger
import org.junit.Assert.assertEquals import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotEquals import org.junit.Assert.assertNotEquals
import org.junit.Assert.assertSame
import org.junit.Test import org.junit.Test
import org.oxycblt.musikr.tag.Name import org.oxycblt.musikr.tag.Name
import org.oxycblt.musikr.tag.Placeholder import org.oxycblt.musikr.tag.Placeholder
@@ -302,6 +304,34 @@ class NamingTest {
assertEquals(Token.Type.LEXICOGRAPHIC, only.type) assertEquals(Token.Type.LEXICOGRAPHIC, only.type)
} }
@Test
fun name_intelligent_sameEffectiveName_reusesTokens() {
val naming = Naming.intelligent()
val first = naming.name("The Same", "Same")
val second = naming.name("Same", "Same")
assertSame(first.tokens, second.tokens)
}
@Test
fun name_intelligent_distinctNames_reusesThreadTransliterator() {
val acquisitions = AtomicInteger()
val transliterate = { name: String -> name }
val naming =
IntelligentNaming(
transliteratorFactory = {
acquisitions.incrementAndGet()
transliterate
}
)
naming.name("First name", null)
naming.name("Second name", null)
assertEquals(1, acquisitions.get())
}
@Test @Test
fun name_equals_simple() { fun name_equals_simple() {
val a = Naming.simple().name("The Same", "Same") val a = Naming.simple().name("The Same", "Same")
@@ -321,10 +321,22 @@ class TagFieldsTest {
assertEquals(listOf("Classical", "Ambient"), metadata.genreNames()) assertEquals(listOf("Classical", "Ambient"), metadata.genreNames())
} }
@Test
fun metadata_replayGainTrack_apePreferredOverId3v2() {
val metadata =
createTestMetadata(
id3v2Tags = mapOf("TXXX:REPLAYGAIN_TRACK_GAIN" to listOf("-1.0 dB")),
apeTags = mapOf("REPLAYGAIN_TRACK_GAIN" to listOf("-5.175 dB")),
)
assertEquals(-5.175f, metadata.replayGainTrackAdjustment()!!, 0.0001f)
}
private fun createTestMetadata( private fun createTestMetadata(
id3v2Tags: Map<String, List<String>> = emptyMap(), id3v2Tags: Map<String, List<String>> = emptyMap(),
xiphTags: Map<String, List<String>> = emptyMap(), xiphTags: Map<String, List<String>> = emptyMap(),
mp4Tags: Map<String, List<String>> = emptyMap(), mp4Tags: Map<String, List<String>> = emptyMap(),
apeTags: Map<String, List<String>> = emptyMap(),
cover: ByteArray? = null, cover: ByteArray? = null,
durationMs: Long = 1000, durationMs: Long = 1000,
bitrateKbps: Int = 320, bitrateKbps: Int = 320,
@@ -332,6 +344,6 @@ class TagFieldsTest {
mimeType: String = "audio/mpeg", mimeType: String = "audio/mpeg",
): Metadata { ): Metadata {
val properties = Properties(mimeType, durationMs, bitrateKbps, sampleRateHz) val properties = Properties(mimeType, durationMs, bitrateKbps, sampleRateHz)
return Metadata(id3v2Tags, xiphTags, mp4Tags, cover, properties) return Metadata(id3v2Tags, xiphTags, mp4Tags, apeTags, cover, properties)
} }
} }
@@ -185,6 +185,6 @@ class TagParserTest {
mimeType: String = "audio/mpeg", mimeType: String = "audio/mpeg",
): Metadata { ): Metadata {
val properties = Properties(mimeType, durationMs, bitrateKbps, sampleRateHz) val properties = Properties(mimeType, durationMs, bitrateKbps, sampleRateHz)
return Metadata(id3v2Tags, xiphTags, mp4Tags, cover, properties) return Metadata(id3v2Tags, xiphTags, mp4Tags, emptyMap(), cover, properties)
} }
} }
@@ -243,6 +243,6 @@ class TagParsingEdgeCasesTest {
mimeType: String = "audio/mpeg", mimeType: String = "audio/mpeg",
): Metadata { ): Metadata {
val properties = Properties(mimeType, durationMs, bitrateKbps, sampleRateHz) val properties = Properties(mimeType, durationMs, bitrateKbps, sampleRateHz)
return Metadata(id3v2Tags, xiphTags, mp4Tags, cover, properties) return Metadata(id3v2Tags, xiphTags, mp4Tags, emptyMap(), cover, properties)
} }
} }