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
81 changed files with 6538 additions and 287 deletions
+4 -2
View File
@@ -16,8 +16,8 @@ android {
defaultConfig {
applicationId namespace
versionName "4.1.5-fork.3"
versionCode 78
versionName "4.1.5-fork.6"
versionCode 81
minSdk min_sdk
// randomly flickers between deprecated and required depending on what mood my gradle is in
@@ -93,6 +93,8 @@ kotlin {
dependencies {
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.ext:junit:1.3.0"
@@ -131,6 +131,7 @@ class MainFragment :
// --- QUEUE SHEET SETUP ---
binding.queueClear.setOnClickListener { queueModel.clearQueue() }
binding.queueShuffle.setOnClickListener { queueModel.shuffleDeck() }
elevationNormal = binding.context.getDimen(MR.dimen.m3_sys_elevation_level1)
@@ -234,7 +235,7 @@ class MainFragment :
collectImmediately(listModel.selected, selectionBackCallback::invalidateEnabled)
collectImmediately(playbackModel.song, ::updateSong)
collectImmediately(playbackModel.openPanel.flow, ::handlePanel)
collectImmediately(queueModel.queue, ::updateQueueClearButton)
collectImmediately(queueModel.queue, ::updateQueueButtons)
}
override fun onStart() {
@@ -656,8 +657,11 @@ class MainFragment :
}
}
private fun updateQueueClearButton(queue: List<Song>) {
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() {
@@ -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
@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 javax.inject.Inject
import kotlinx.coroutines.CancellationException
import org.oxycblt.auxio.BuildConfig
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.withContext
@@ -245,6 +246,7 @@ constructor(
private val storedPlaylists: StoredPlaylists,
private val settingCovers: SettingCovers,
private val musicSettings: MusicSettings,
private val snapshotRestorer: SnapshotRestorer,
) : MusicRepository {
private val updateListeners = mutableListOf<MusicRepository.UpdateListener>()
private val indexingListeners = mutableListOf<MusicRepository.IndexingListener>()
@@ -256,6 +258,8 @@ constructor(
override val indexingState: IndexingState?
get() = currentIndexingState ?: previousCompletedState
private val snapshotRestoration = snapshotRestorer.start()
@Synchronized
override fun addUpdateListener(listener: MusicRepository.UpdateListener) {
L.d("Adding $listener to update listeners")
@@ -381,6 +385,10 @@ constructor(
private suspend fun indexImpl(withCache: Boolean) {
L.d("Index requested, initializing")
val snapshot = snapshotRestoration.await()
if (snapshot != null && !snapshot.empty()) {
emitLibrary(snapshot)
}
// Obtain configuration information
val separators = Separators.from(musicSettings.separators)
L.d("Separators: $separators")
@@ -411,6 +419,15 @@ constructor(
val start = System.currentTimeMillis()
val result = Musikr.new(context, config).run(::emitIndexingProgress)
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
// later.
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.
L.d("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.
L.d("Indexing complete")
emitIndexingCompletion(null)
@@ -53,6 +53,7 @@ class MusicViewModel
constructor(
@ApplicationContext context: Context,
private val listSettings: ListSettings,
private val musicSettings: MusicSettings,
private val musicRepository: MusicRepository,
) : ViewModel(), MusicRepository.UpdateListener, MusicRepository.IndexingListener {
private val externalPlaylistManager = ExternalPlaylistManager.from(context)
@@ -160,24 +161,19 @@ constructor(
fun importPlaylist(uri: Uri? = null, target: Playlist? = null) {
if (uri != null) {
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) {
L.e("Could not import playlist")
playlistMessage.put(PlaylistMessage.ImportFailed)
return@launch
}
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
}
val songs = importedPlaylist.songs
if (target !== null) {
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.playback.state.PlaybackStateManager
import org.oxycblt.auxio.util.getSystemServiceCompat
import org.oxycblt.musikr.Library
import org.oxycblt.musikr.MusicParent
import org.oxycblt.musikr.fs.mediastore.MediaStore
import org.oxycblt.musikr.fs.saf.SAF
@@ -155,19 +156,7 @@ private constructor(
L.d("Music changed, updating shared objects")
// Wipe possibly-invalidated outdated covers
imageLoader.memoryCache?.clear()
// Clear invalid models from PlaybackStateManager. 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,
)
}
reconcilePlaybackState(playbackManager, library, musicRepository)
}
private fun startTracking() {
@@ -232,5 +221,30 @@ private constructor(
companion object {
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,
)
}
}
}
}
@@ -167,6 +167,12 @@ class QueueViewModel @Inject constructor(private val playbackManager: PlaybackSt
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
@@ -287,6 +287,53 @@ class ExoPlaybackStateHolder(
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() {
// 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
@@ -145,6 +145,15 @@ interface PlaybackStateHolder {
*/
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.
*
@@ -206,6 +215,9 @@ sealed interface StateAck {
/** @see PlaybackStateHolder.shuffled */
data object QueueReordered : StateAck
/** @see PlaybackStateHolder.shuffleDeck */
data object ShuffleDeck : StateAck
/**
* @see PlaybackStateHolder.newPlayback
* @see PlaybackStateHolder.applySavedState
@@ -204,6 +204,12 @@ interface PlaybackStateManager {
*/
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
@@ -618,6 +624,17 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
}
}
@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
@@ -874,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 -> {
val rawQueue = stateHolder.resolveQueue()
stateMirror =
@@ -114,6 +114,14 @@
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"
+11
View File
@@ -126,6 +126,17 @@
app:layout_constraintEnd_toEndOf="@+id/queue_handle"
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"
@@ -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
}
}
}
@@ -78,6 +78,15 @@ class DeckRowDiffTest {
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())
@@ -47,6 +47,9 @@ class FakePlaybackStateHolder : PlaybackStateHolder {
/** Every [StateAck.PlayNext] receipt handed to this holder, in order. */
val insertions = mutableListOf<StateAck.PlayNext>()
/** Every [StateAck.ShuffleDeck] receipt handed to this holder, in order. */
val shuffles = mutableListOf<StateAck.ShuffleDeck>()
var rawQueue = RawQueue.nil()
private set
@@ -225,6 +228,18 @@ class FakePlaybackStateHolder : PlaybackStateHolder {
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 applySavedState(
@@ -242,7 +257,10 @@ class FakePlaybackStateHolder : PlaybackStateHolder {
override fun endSession() {}
override fun reset(ack: StateAck.NewPlayback) {}
override fun reset(ack: StateAck.NewPlayback) {
rawQueue = RawQueue.nil()
manager?.ack(this, ack)
}
}
/**
@@ -255,6 +255,58 @@ class PlaybackStateManagerImplTest {
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
* rest of the deck survives, matching the heap's own realignment.
+2 -4
View File
@@ -85,12 +85,10 @@ dependencies {
tasks.register("assembleTaglib", Exec, {
def jniDir = "$projectDir/src/main/cpp"
def libs = new File("$jniDir/taglib/pkg")
if (libs.exists()) {
commandLine "true"
return
}
def ndkDir = androidComponents.sdkComponents.ndkDirectory.get().asFile
commandLine "sh", "-c", "$jniDir/build_taglib.sh $jniDir $ndkDir"
onlyIf { !libs.exists() }
mustRunAfter(tasks.named("clean"))
})
afterEvaluate {
+11 -3
View File
@@ -32,7 +32,7 @@
#include "JByteArrayRef.h"
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) {
@@ -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) {
for (auto field : tag.fieldListMap()) {
auto key = field.first.upper();
@@ -203,15 +210,16 @@ jobject JMetadataBuilder::build() {
JClassRef jMetadataClass { env, "org/oxycblt/musikr/metadata/Metadata" };
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");
auto jId3v2Map = id3v2.getObject();
auto jXiphMap = xiph.getObject();
auto jMp4Map = mp4.getObject();
auto jApeMap = ape.getObject();
if (cover.has_value()) {
JByteArrayRef jCoverArray { env, cover.value() };
jobject result = env->NewObject(*jMetadataClass, jMetadataInitMethod,
**jId3v2Map, **jXiphMap, **jMp4Map, *jCoverArray, *jProperties);
**jId3v2Map, **jXiphMap, **jMp4Map, **jApeMap, *jCoverArray, *jProperties);
return result;
}
return env->NewObject(*jMetadataClass, jMetadataInitMethod, **jId3v2Map,
+3
View File
@@ -27,6 +27,7 @@
#include "taglib/id3v2tag.h"
#include "taglib/xiphcomment.h"
#include "taglib/mp4tag.h"
#include "taglib/apetag.h"
#include "taglib/audioproperties.h"
#include "JTagMap.h"
@@ -40,6 +41,7 @@ public:
void setId3v2(TagLib::ID3v2::Tag &tag);
void setXiph(TagLib::Ogg::XiphComment &tag);
void setMp4(TagLib::MP4::Tag &tag);
void setApe(TagLib::APE::Tag &tag);
void setFlacPictures(TagLib::List<TagLib::FLAC::Picture*> &pics);
void setProperties(TagLib::AudioProperties *properties);
@@ -56,6 +58,7 @@ private:
JTagMap id3v2;
JTagMap xiph;
JTagMap mp4;
JTagMap ape;
};
#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} \
-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 \
-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"
# Try to parallelize the build
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());
}
}
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;
}
@@ -19,9 +19,14 @@
package org.oxycblt.musikr
import android.content.Context
import android.os.SystemClock
import java.util.Collections
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
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.ExploreStep
import org.oxycblt.musikr.pipeline.Explored
@@ -48,7 +53,8 @@ interface Musikr {
* 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
* 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.
*/
suspend fun run(onProgress: suspend (IndexingProgress) -> Unit = {}): LibraryResult
@@ -106,6 +112,44 @@ sealed interface 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 val config: Config,
private val exploreStep: ExploreStep,
@@ -113,19 +157,22 @@ private class MusikrImpl(
private val evaluateStep: EvaluateStep,
) : Musikr {
override suspend fun run(onProgress: suspend (IndexingProgress) -> Unit) = coroutineScope {
val progressCoalescer = IndexingProgressCoalescer(onProgress = onProgress)
onProgress(IndexingProgress.Songs(0, 0))
var explored = 0
var loaded = 0
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 trackedExploredTask =
tryAsyncWith(trackedExploredChannel, Dispatchers.Main) {
for (item in exploredChannel) {
explored++
onProgress(IndexingProgress.Songs(loaded, explored))
progressCoalescer.submit(IndexingProgress.Songs(loaded, explored))
trackedExploredChannel.send(item)
}
progressCoalescer.flush()
}
val extractedChannel = Channel<Extracted>(Channel.UNLIMITED)
val extractedTask = extractStep.extract(this, trackedExploredChannel, extractedChannel)
@@ -134,12 +181,13 @@ private class MusikrImpl(
tryAsyncWith(trackedExtractedChannel, Dispatchers.Main) {
for (item in extractedChannel) {
loaded++
onProgress(IndexingProgress.Songs(loaded, explored))
progressCoalescer.submit(IndexingProgress.Songs(loaded, explored))
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()
LibraryResultImpl(config, library)
}
@@ -37,13 +37,16 @@ import org.oxycblt.musikr.tag.parse.ParsedTags
* Create an instance with [from].
*/
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()
override suspend fun read(file: File): CacheResult {
val currentMapping = mappingLock.withLock {
mapping ?: readDao.selectAllSongs().associateBy { it.uri }.also { mapping = it }
}
val currentMapping =
mapping
?: mappingLock.withLock {
mapping ?: readDao.selectAllSongs().associateBy { it.uri }.also { mapping = it }
}
val dbSong = currentMapping[file.uri] ?: return CacheResult.Miss(file)
if (dbSong.modifiedMs != file.modifiedMs) {
return CacheResult.Stale(file, dbSong.addedMs)
@@ -50,6 +50,15 @@ private const val PREFIX = "mcf:"
* @param context The [Context] to use to access the filesystem and check for ID validity.
*/
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> {
if (!id.startsWith(PREFIX)) {
return CoverResult.Miss()
@@ -70,6 +70,8 @@ interface CoverStorage {
suspend fun rm(name: String)
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
* location.
@@ -40,6 +40,15 @@ private const val PREFIX = "mcs:"
* @param coverStorage The [CoverStorage] to use to obtain the cover data.
*/
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> {
if (!id.startsWith(PREFIX)) {
return CoverResult.Miss()
@@ -24,6 +24,9 @@ import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
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>>
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.File
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.VolumeManager
import org.oxycblt.musikr.fs.saf.contentResolverSafe
@@ -54,6 +55,15 @@ private constructor(
) : FS {
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)
override suspend fun explore(files: Channel<File>): Deferred<Result<Unit>> = coroutineScope {
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 {
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 =
InternalVolumeImpl(storageManager.primaryStorageVolume)
storageManager.primaryStorageVolume.toInternalValue(context)
override fun getVolumes() =
override fun getVolumes(): List<Volume> =
storageManager.storageVolumesCompat.map {
if (it.isInternalCompat) {
InternalVolumeImpl(it)
it.toInternalValue(context)
} else {
ExternalVolumeImpl(it)
it.toExternalValue(context)
}
}
private data class InternalVolumeImpl(val storageVolume: StorageVolume) : Volume.Internal {
override val mediaStoreName
get() = storageVolume.mediaStoreVolumeNameCompat
override val components
get() = storageVolume.directoryCompat?.let(Components.Companion::parseUnix)
override fun resolveName(context: Context) = storageVolume.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)
}
}
private fun StorageVolume.toInternalValue(context: Context) =
InternalVolumeValue(
mediaStoreName = mediaStoreVolumeNameCompat,
components = directoryCompat?.let(Components.Companion::parseUnix),
displayName = getDescriptionCompat(context),
)
private fun StorageVolume.toExternalValue(context: Context) =
ExternalVolumeValue(
id = uuidCompat,
mediaStoreName = mediaStoreVolumeNameCompat,
components = directoryCompat?.let(Components.Companion::parseUnix),
displayName = getDescriptionCompat(context),
)
@@ -54,6 +54,9 @@ private constructor(
private val contentResolver: ContentResolver,
private val query: Query,
) : FS {
override val locationRoots: List<Path>
get() = query.source.map { it.path }
override suspend fun explore(files: Channel<File>): Deferred<Result<Unit>> = coroutineScope {
tryAsyncWith(files, Dispatchers.Main) {
query.source
@@ -22,6 +22,7 @@ data class Metadata(
val id3v2: Map<String, List<String>>,
val xiph: Map<String, List<String>>,
val mp4: Map<String, List<String>>,
val ape: Map<String, List<String>>,
val cover: ByteArray?,
val properties: Properties,
) {
@@ -34,6 +35,7 @@ data class Metadata(
if (id3v2 != other.id3v2) return false
if (xiph != other.xiph) return false
if (mp4 != other.mp4) return false
if (ape != other.ape) return false
if (cover != null) {
if (other.cover == null) return false
if (!cover.contentEquals(other.cover)) return false
@@ -47,6 +49,7 @@ data class Metadata(
var result = id3v2.hashCode()
result = 31 * result + xiph.hashCode()
result = 31 * result + mp4.hashCode()
result = 31 * result + ape.hashCode()
result = 31 * result + (cover?.contentHashCode() ?: 0)
result = 31 * result + properties.hashCode()
return result
@@ -40,7 +40,7 @@ internal interface SongCore {
* @author Alexander Capehart (OxygenCobalt)
*/
internal class SongImpl(private val handle: SongCore) : Song {
private val preSong = handle.preSong
internal val preSong = handle.preSong
override val uid = preSong.v363Uid
@@ -19,24 +19,39 @@
package org.oxycblt.musikr.pipeline
import android.content.Context
import java.util.zip.CRC32
import java.util.zip.CheckedInputStream
import kotlinx.coroutines.channels.Channel
import org.oxycblt.musikr.BuildConfig
import org.oxycblt.musikr.Config
import org.oxycblt.musikr.Interpretation
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.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.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
internal interface EvaluateStep {
suspend fun evaluate(extractedMusic: Channel<Extracted>): MutableLibrary
suspend fun evaluate(
extractedMusic: Channel<Extracted>,
playlistFiles: List<File>,
): MutableLibrary
companion object {
fun new(context: Context, config: Config, interpretation: Interpretation): EvaluateStep =
EvaluateStepImpl(
context,
config.fs,
TagInterpreter.new(interpretation),
PlaylistInterpreter.new(interpretation),
config.storage.storedPlaylists,
@@ -47,21 +62,37 @@ internal interface EvaluateStep {
private class EvaluateStepImpl(
private val context: Context,
private val fs: FS,
private val tagInterpreter: TagInterpreter,
private val playlistInterpreter: PlaylistInterpreter,
private val storedPlaylists: StoredPlaylists,
private val libraryFactory: LibraryFactory,
) : 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 preSongs = mutableListOf<PreSong>()
for (extracted in extractedMusic) {
when (extracted) {
is RawSong -> builder.add(tagInterpreter.interpret(extracted))
is RawPlaylist -> builder.add(playlistInterpreter.interpret(extracted.file))
is RawSong -> {
val preSong = tagInterpreter.interpret(extracted)
preSongs.add(preSong)
builder.add(preSong)
}
is NotAudio -> {}
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()
// Render graph to Graphviz in debug mode
@@ -72,4 +103,77 @@ private class EvaluateStepImpl(
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
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 {
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(
scope: CoroutineScope,
explored: Channel<Explored>,
playlistFiles: MutableList<File>,
): Deferred<Result<Unit>> {
val files = Channel<File>(Channel.UNLIMITED)
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/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)
}
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 =
scope.tryAsyncWith(explored, Dispatchers.Main) {
for (item in finalized) {
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
@@ -73,7 +73,6 @@ private class ExtractStepImpl(
scope.mapParallel(PARALLELISM, explored, extract, Dispatchers.IO) { item ->
when (item) {
is RawSong -> Finalized(item)
is RawPlaylist -> Finalized(item)
is NewSong -> {
when (val result = metadataExtractor.extract(item.file)) {
is MetadataResult.Success ->
@@ -21,7 +21,6 @@ package org.oxycblt.musikr.pipeline
import org.oxycblt.musikr.covers.Cover
import org.oxycblt.musikr.fs.File
import org.oxycblt.musikr.metadata.Properties
import org.oxycblt.musikr.playlist.PlaylistFile
import org.oxycblt.musikr.tag.parse.ParsedTags
internal sealed interface PipelineItem
@@ -48,8 +47,6 @@ internal data object InvalidSong : Extracted.Invalid
internal data object NotAudio : Explored.Known, Extracted.Valid
internal data class RawPlaylist(val file: PlaylistFile) : Explored.Known, Extracted.Valid
internal data class RawSong(
val file: File,
val properties: Properties,
@@ -20,7 +20,9 @@ package org.oxycblt.musikr.playlist
import android.content.Context
import android.net.Uri
import org.oxycblt.musikr.Library
import org.oxycblt.musikr.Playlist
import org.oxycblt.musikr.Song
import org.oxycblt.musikr.fs.Components
import org.oxycblt.musikr.fs.Path
import org.oxycblt.musikr.fs.Volume
@@ -37,13 +39,16 @@ import org.oxycblt.musikr.playlist.m3u.M3U
*/
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.
* @return An [ImportedPlaylist] containing the paths to the files listed in the playlist file,
* or null if the playlist could not be imported.
* @param roots Candidate roots to resolve entries against after the playlist file's own
* 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].
@@ -60,7 +65,7 @@ interface ExternalPlaylistManager {
ExternalPlaylistManagerImpl(
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.
*
* @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 M3U
*/
data class ImportedPlaylist(val name: String?, val paths: List<PossiblePaths>)
typealias PossiblePaths = List<Path>
data class ImportedPlaylist(val name: String?, val songs: List<Song>)
private class ExternalPlaylistManagerImpl(
private val context: Context,
private val documentPathFactory: DocumentPathFactory,
private val m3u: M3U,
) : 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 =
documentPathFactory.unpackDocumentUri(uri)
?: Path(Volume.ThirdParty(uri), Components.root())
return try {
context.contentResolverSafe.openInputStream(uri)?.use {
val imported = m3u.read(it, filePath.directory) ?: return null
val name = imported.name
val parsed = m3u.read(it) ?: return null
val paths =
resolver.resolve(parsed.entries, listOf(filePath.directory) + roots) { path ->
library.findSongByPath(path) != null
}
?: return null
val songs = paths.mapNotNull(library::findSongByPath)
val name = parsed.name
if (name != null) {
return imported
return ImportedPlaylist(name, songs)
}
// Strip extension
val fileName = filePath.name ?: return imported
val split = fileName.split(".")
var newName = split[0]
// Replace delimiters with space
newName = newName.replace(Regex("[_-]"), " ")
// Replace long stretches of whitespace with one space
newName = newName.replace(Regex("\\s+"), " ")
return ImportedPlaylist(newName, imported.paths)
val fileName = filePath.name ?: return ImportedPlaylist(null, songs)
return ImportedPlaylist(playlistNameFromFileName(fileName), songs)
}
} catch (e: Exception) {
null
@@ -43,3 +43,13 @@ internal interface PlaylistHandle {
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(
entities = [PlaylistInfo::class, PlaylistSong::class, PlaylistSongCrossRef::class],
version = 75,
version = 76,
exportSchema = false,
)
@TypeConverters(Music.UID.TypeConverters::class)
@@ -117,7 +117,15 @@ internal abstract class PlaylistDatabase : RoomDatabase() {
washUids(db, "PlaylistInfo", "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)
.build()
@@ -143,6 +151,16 @@ internal abstract class PlaylistDao {
@Query("SELECT * FROM PlaylistInfo")
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.
*
@@ -46,7 +46,15 @@ internal data class RawPlaylist(
*
* @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.
@@ -23,11 +23,32 @@ import org.oxycblt.musikr.Music
import org.oxycblt.musikr.Song
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.util.unlikelyToBeNull
abstract class StoredPlaylists {
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>
companion object {
@@ -43,6 +64,42 @@ private class StoredPlaylistsImpl(private val playlistDao: PlaylistDao) : Stored
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() =
playlistDao.readRawPlaylists().map {
PlaylistFile(
@@ -18,7 +18,6 @@
package org.oxycblt.musikr.playlist.m3u
import android.content.Context
import java.io.BufferedReader
import java.io.BufferedWriter
import java.io.InputStream
@@ -27,11 +26,8 @@ import java.io.OutputStream
import org.oxycblt.musikr.Playlist
import org.oxycblt.musikr.fs.Components
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.ImportedPlaylist
import org.oxycblt.musikr.playlist.PossiblePaths
import org.oxycblt.musikr.playlist.PlaylistPathResolver
import org.oxycblt.musikr.tag.Name
import org.oxycblt.musikr.util.correctWhitespace
import org.oxycblt.musikr.util.unlikelyToBeNull
@@ -43,15 +39,13 @@ import org.oxycblt.musikr.util.unlikelyToBeNull
*/
abstract class M3U {
/**
* Reads an M3U file from the given [stream] and returns a [ImportedPlaylist] containing the
* paths to the files listed in the M3U file.
* Reads an M3U file from the given [stream] and returns the parsed [ParsedM3U]. Entries are
* interpreted but not resolved against the library — see [PlaylistPathResolver].
*
* @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
* resolve relative paths.
* @return An [ImportedPlaylist] containing the paths to the files listed in the M3U file,
* @return The [ParsedM3U], or null if the file contained no entries.
*/
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,.
@@ -73,15 +67,22 @@ abstract class M3U {
/** The mime type used for M3U files by the android system. */
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? {
val volumes = volumeManager.getVolumes()
/**
* The raw result of parsing an M3U file.
*
* @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 paths = mutableListOf<PossiblePaths>()
val entries = mutableListOf<PlaylistPathResolver.Entry>()
var name: String? = null
consumeFile@ while (true) {
@@ -112,63 +113,43 @@ private class M3UImpl(private val volumeManager: VolumeManager) : M3U() {
}
}
// There is basically no formal specification of file paths in M3U, and it differs
// based on the programs that generated it. I more or less have to consider any possible
// interpretation as valid.
val interpretations = interpretPath(unlikelyToBeNull(path))
val possibilities = interpretations.flatMap {
expandInterpretation(it, workingDirectory, volumes)
}
paths.add(possibilities)
// One interpretation per line: resolution against the library happens later, in
// PlaylistPathResolver.
entries.add(interpretLine(unlikelyToBeNull(path)))
}
return if (paths.isNotEmpty()) {
ImportedPlaylist(name, paths)
return if (entries.isNotEmpty()) {
ParsedM3U(name, entries)
} else {
// Couldn't get anything useful out of this file.
null
}
}
private data class InterpretedPath(val components: Components, val likelyAbsolute: Boolean)
private fun interpretPath(path: String): List<InterpretedPath> =
/**
* Interpret a line as an entry. There is no formal specification of M3U paths, so the form
* 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 {
path.startsWith('/') -> listOf(InterpretedPath(Components.parseUnix(path), true))
path.startsWith("./") -> listOf(InterpretedPath(Components.parseUnix(path), false))
path.startsWith('/') ->
PlaylistPathResolver.Entry(Components.parseUnix(path), absolute = true)
path.startsWith("./") ->
PlaylistPathResolver.Entry(Components.parseUnix(path), absolute = false)
path.matches(WINDOWS_VOLUME_PREFIX_REGEX) ->
listOf(InterpretedPath(Components.parseWindows(path.substring(2)), true))
path.startsWith("\\") -> listOf(InterpretedPath(Components.parseWindows(path), true))
path.startsWith(".\\") -> listOf(InterpretedPath(Components.parseWindows(path), false))
else ->
listOf(
InterpretedPath(Components.parseUnix(path), false),
InterpretedPath(Components.parseWindows(path), true),
PlaylistPathResolver.Entry(
Components.parseWindows(path.substring(2)), absolute = true
)
path.startsWith("\\") ->
PlaylistPathResolver.Entry(Components.parseWindows(path), absolute = true)
path.startsWith(".\\") ->
PlaylistPathResolver.Entry(Components.parseWindows(path), absolute = false)
'\\' in path ->
PlaylistPathResolver.Entry(Components.parseWindows(path), absolute = false)
else -> PlaylistPathResolver.Entry(Components.parseUnix(path), absolute = false)
}
private fun expandInterpretation(
path: InterpretedPath,
workingDirectory: Path,
volumes: List<Volume>,
): List<Path> {
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(
playlist: Playlist,
outputStream: OutputStream,
@@ -232,22 +213,6 @@ private class M3UImpl(private val volumeManager: VolumeManager) : M3U() {
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 {
// 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
@@ -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. */
class Token internal constructor(internal val collationKey: CollationKey, internal val type: Type) :
Comparable<Token> {
@@ -22,6 +22,8 @@ import android.icu.text.Transliterator
import android.os.Build
import java.text.CollationKey
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.Placeholder
import org.oxycblt.musikr.tag.Token
@@ -37,105 +39,108 @@ abstract class Naming {
abstract fun name(raw: String, sort: String?): Name.Known
companion object {
fun intelligent(): Naming = IntelligentNaming
fun intelligent(): Naming = IntelligentNaming()
fun simple(): Naming = SimpleNaming
}
}
data object IntelligentNaming : Naming() {
override fun name(raw: String, sort: String?): Name.Known = IntelligentKnownName(raw, sort)
class IntelligentNaming(
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() {
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 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.
/**
* 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 {
// Remove excess punctuation from the string, as those usually aren't considered in sorting.
val stripped = name.replace(punctRegex, "").trim().ifEmpty { name }
val collationKey = collator.getCollationKey(stripped)
// Always use lexicographic mode since we aren't parsing any numeric components
return Token(collationKey, Token.Type.LEXICOGRAPHIC)
}
private fun parseToken(name: String): Token {
// Remove excess punctuation from the string, as those usually aren't considered in sorting.
val stripped = name.replace(punctRegex, "").trim().ifEmpty { name }
val collationKey = collator.getCollationKey(stripped)
// Always use lexicographic mode since we aren't parsing any numeric components.
return Token(collationKey, Token.Type.LEXICOGRAPHIC)
}
/**
* [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 simpleTokens(raw: String, sort: String?) = listOf(parseToken(sort ?: raw))
private fun parseTokens(name: String): List<Token> {
// TODO: This routine is consuming much of the song building runtime, find a way to
// optimize it
var stripped =
name
// Replace punctuation with spaces to create token boundaries, improving
// sorting of names like "15-9" vs "15-10".
.replace(punctRegex, " ")
.let { it.ifBlank { name } }
.run {
// Strip any english articles like "the" or "an" from the start, as music
// sorting should ignore such when possible.
when {
length > 4 && startsWith("the ", ignoreCase = true) -> substring(4)
length > 3 && startsWith("an ", ignoreCase = true) -> substring(3)
length > 2 && startsWith("a ", ignoreCase = true) -> substring(2)
else -> this
}
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
// optimize it
var stripped =
name
// Replace punctuation with spaces to create token boundaries, improving
// sorting of names like "15-9" vs "15-10".
.replace(punctRegex, " ")
.let { it.ifBlank { name } }
.run {
// Strip any english articles like "the" or "an" from the start, as music
// sorting should ignore such when possible.
when {
length > 4 && startsWith("the ", ignoreCase = true) -> substring(4)
length > 3 && startsWith("an ", ignoreCase = true) -> substring(3)
length > 2 && startsWith("a ", ignoreCase = true) -> substring(2)
else -> this
}
// Transliterate to latin if available
if (
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
// individual lexicographic and numeric tokens and then individually compare them
// with special logic.
return TOKEN_REGEX.findAll(stripped).mapTo(mutableListOf()) { match ->
// Remove excess whitespace where possible
val token = match.value.trim().ifEmpty { match.value }
val collationKey: CollationKey
val type: Token.Type
// Separate each token into their numeric and lexicographic counterparts.
if (token.first().isDigit()) {
// The digit string comparison breaks with preceding zero digits, remove those
val digits =
token.trimStart { Character.getNumericValue(it) == 0 }.ifEmpty { token }
// Other languages have other types of digit strings, still use collation keys
collationKey = collator.getCollationKey(digits)
type = Token.Type.NUMERIC
} else {
collationKey = collator.getCollationKey(token)
type = Token.Type.LEXICOGRAPHIC
}
Token(collationKey, type)
}
}
companion object {
private val TOKEN_REGEX by lazy { Regex("(\\d+)|(\\D+)") }
// Transliterate to latin if available
stripped = transliterate(stripped)
// To properly compare numeric components in names, we have to split them up into
// individual lexicographic and numeric tokens and then individually compare them
// with special logic.
return TOKEN_REGEX.findAll(stripped).mapTo(mutableListOf()) { match ->
// Remove excess whitespace where possible
val token = match.value.trim().ifEmpty { match.value }
val collationKey: CollationKey
val type: Token.Type
// Separate each token into their numeric and lexicographic counterparts.
if (token.first().isDigit()) {
// The digit string comparison breaks with preceding zero digits, remove those
val digits = token.trimStart { Character.getNumericValue(it) == 0 }.ifEmpty { token }
// Other languages have other types of digit strings, still use collation keys
collationKey = collator.getCollationKey(digits)
type = Token.Type.NUMERIC
} else {
collationKey = collator.getCollationKey(token)
type = Token.Type.LEXICOGRAPHIC
}
Token(collationKey, type)
}
}
@@ -253,15 +253,18 @@ internal fun Metadata.isCompilation() =
?: id3v2["TXXX:COMPILATION"]
?: 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() =
(xiph["R128_TRACK_GAIN"]?.parseR128Adjustment()
(ape["REPLAYGAIN_TRACK_GAIN"]?.parseReplayGainAdjustment()
?: xiph["R128_TRACK_GAIN"]?.parseR128Adjustment()
?: xiph["REPLAYGAIN_TRACK_GAIN"]?.parseReplayGainAdjustment()
?: mp4["----:COM.APPLE.ITUNES:REPLAYGAIN_TRACK_GAIN"]?.parseReplayGainAdjustment()
?: id3v2["TXXX:REPLAYGAIN_TRACK_GAIN"]?.parseReplayGainAdjustment())
internal fun Metadata.replayGainAlbumAdjustment() =
(xiph["R128_ALBUM_GAIN"]?.parseR128Adjustment()
(ape["REPLAYGAIN_ALBUM_GAIN"]?.parseReplayGainAdjustment()
?: xiph["R128_ALBUM_GAIN"]?.parseR128Adjustment()
?: xiph["REPLAYGAIN_ALBUM_GAIN"]?.parseReplayGainAdjustment()
?: mp4["----:COM.APPLE.ITUNES: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
import java.util.concurrent.atomic.AtomicInteger
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotEquals
import org.junit.Assert.assertSame
import org.junit.Test
import org.oxycblt.musikr.tag.Name
import org.oxycblt.musikr.tag.Placeholder
@@ -302,6 +304,34 @@ class NamingTest {
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
fun name_equals_simple() {
val a = Naming.simple().name("The Same", "Same")
@@ -321,10 +321,22 @@ class TagFieldsTest {
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(
id3v2Tags: Map<String, List<String>> = emptyMap(),
xiphTags: Map<String, List<String>> = emptyMap(),
mp4Tags: Map<String, List<String>> = emptyMap(),
apeTags: Map<String, List<String>> = emptyMap(),
cover: ByteArray? = null,
durationMs: Long = 1000,
bitrateKbps: Int = 320,
@@ -332,6 +344,6 @@ class TagFieldsTest {
mimeType: String = "audio/mpeg",
): Metadata {
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",
): Metadata {
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",
): Metadata {
val properties = Properties(mimeType, durationMs, bitrateKbps, sampleRateHz)
return Metadata(id3v2Tags, xiphTags, mp4Tags, cover, properties)
return Metadata(id3v2Tags, xiphTags, mp4Tags, emptyMap(), cover, properties)
}
}