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
53 changed files with 5522 additions and 139 deletions
+4 -2
View File
@@ -16,8 +16,8 @@ android {
defaultConfig { defaultConfig {
applicationId namespace applicationId namespace
versionName "4.1.5-fork.4" versionName "4.1.5-fork.6"
versionCode 79 versionCode 81
minSdk min_sdk minSdk min_sdk
// randomly flickers between deprecated and required depending on what mood my gradle is in // randomly flickers between deprecated and required depending on what mood my gradle is in
@@ -93,6 +93,8 @@ kotlin {
dependencies { dependencies {
testImplementation "junit:junit:4.13.2" testImplementation "junit:junit:4.13.2"
testImplementation "io.mockk:mockk:1.14.11"
testImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:$kotlin_coroutines_version"
androidTestImplementation "androidx.test:runner:1.7.0" androidTestImplementation "androidx.test:runner:1.7.0"
androidTestImplementation "androidx.test.ext:junit:1.3.0" androidTestImplementation "androidx.test.ext:junit:1.3.0"
@@ -131,6 +131,7 @@ class MainFragment :
// --- QUEUE SHEET SETUP --- // --- QUEUE SHEET SETUP ---
binding.queueClear.setOnClickListener { queueModel.clearQueue() } binding.queueClear.setOnClickListener { queueModel.clearQueue() }
binding.queueShuffle.setOnClickListener { queueModel.shuffleDeck() }
elevationNormal = binding.context.getDimen(MR.dimen.m3_sys_elevation_level1) elevationNormal = binding.context.getDimen(MR.dimen.m3_sys_elevation_level1)
@@ -234,7 +235,7 @@ class MainFragment :
collectImmediately(listModel.selected, selectionBackCallback::invalidateEnabled) collectImmediately(listModel.selected, selectionBackCallback::invalidateEnabled)
collectImmediately(playbackModel.song, ::updateSong) collectImmediately(playbackModel.song, ::updateSong)
collectImmediately(playbackModel.openPanel.flow, ::handlePanel) collectImmediately(playbackModel.openPanel.flow, ::handlePanel)
collectImmediately(queueModel.queue, ::updateQueueClearButton) collectImmediately(queueModel.queue, ::updateQueueButtons)
} }
override fun onStart() { 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() requireBinding().queueClear.isVisible = queue.isNotEmpty()
// Shuffling fewer than two waiting entries cannot change anything.
val waiting = queue.size - if (queueModel.index.value == 0) 1 else 0
requireBinding().queueShuffle.isVisible = waiting >= 2
} }
private fun tryClosePlaybackPanel() { private fun tryClosePlaybackPanel() {
@@ -0,0 +1,144 @@
/*
* Copyright (c) 2026 Auxio Project
* LibrarySnapshotRestore.kt is part of Auxio.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.oxycblt.auxio.music
import android.content.Context
import java.io.File
import javax.inject.Inject
import org.oxycblt.musikr.Config
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.CancellationException
import org.oxycblt.auxio.image.ImageSettings
import org.oxycblt.auxio.music.locations.LocationMode
import org.oxycblt.musikr.Interpretation
import org.oxycblt.musikr.Library
import org.oxycblt.musikr.MutableLibrary
import org.oxycblt.musikr.fs.mediastore.MediaStore.FilterMode
import org.oxycblt.musikr.playlist.db.StoredPlaylists
import org.oxycblt.musikr.snapshot.LibrarySnapshot
import org.oxycblt.musikr.snapshot.LibrarySnapshotFingerprint
import org.oxycblt.musikr.snapshot.LibrarySnapshotStore
import org.oxycblt.musikr.tag.interpret.Naming
import org.oxycblt.musikr.tag.interpret.Separators
interface SnapshotRestoration {
suspend fun await(): MutableLibrary?
}
class SharedSnapshotRestoration
internal constructor(
scope: CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.IO),
restore: suspend () -> MutableLibrary?,
) : SnapshotRestoration {
private val deferred = scope.async { restore() }
override suspend fun await(): MutableLibrary? {
return try {
deferred.await()
} catch (exception: CancellationException) {
throw exception
} catch (exception: Exception) {
null
}
}
}
interface SnapshotRestorer {
fun start(): SnapshotRestoration
suspend fun capture(library: Library, config: Config) {}
}
class MusikrSnapshotRestorer
@Inject
constructor(
@dagger.hilt.android.qualifiers.ApplicationContext private val context: Context,
private val storedPlaylists: StoredPlaylists,
private val musicSettings: MusicSettings,
private val imageSettings: ImageSettings,
) : SnapshotRestorer {
override fun start(): SnapshotRestoration {
val interpretation =
Interpretation(
if (musicSettings.intelligentSorting) Naming.intelligent() else Naming.simple(),
Separators.from(musicSettings.separators),
)
val fingerprint = fingerprint()
return SharedSnapshotRestoration {
LibrarySnapshot(context, storedPlaylists, interpretation)
.restore(LibrarySnapshotStore(context.filesDir), fingerprint)
}
}
override suspend fun capture(library: Library, config: Config) {
LibrarySnapshot(context, config)
.capture(
library,
LibrarySnapshotStore(context.filesDir),
fingerprint(),
)
}
private fun fingerprint(): LibrarySnapshotFingerprint {
val sourceMode = musicSettings.locationMode
val sourceRoots: List<String>
val excludedRoots: List<String>
val withHidden: Boolean
val excludeNonMusic: Boolean
when (sourceMode) {
LocationMode.SAF -> {
val query = musicSettings.safQuery
sourceRoots = query.source.map { it.uri.toString() }
excludedRoots = query.exclude.map { it.uri.toString() }
withHidden = query.withHidden
excludeNonMusic = false
}
LocationMode.MEDIA_STORE -> {
val query = musicSettings.mediaStoreQuery
sourceRoots =
if (query.mode == FilterMode.INCLUDE) {
query.filtered.map { it.uri.toString() }
} else {
emptyList()
}
excludedRoots =
if (query.mode == FilterMode.EXCLUDE) {
query.filtered.map { it.uri.toString() }
} else {
emptyList()
}
withHidden = false
excludeNonMusic = query.excludeNonMusic
}
}
return LibrarySnapshotFingerprint(
sourceMode = sourceMode.name,
sourceRoots = sourceRoots,
excludedRoots = excludedRoots,
withHidden = withHidden,
excludeNonMusic = excludeNonMusic,
intelligentSorting = musicSettings.intelligentSorting,
separators = musicSettings.separators,
coverMode = imageSettings.coverMode.name,
)
}
}
@@ -30,4 +30,6 @@ interface MusicModule {
@Singleton @Binds fun repository(musicRepository: MusicRepositoryImpl): MusicRepository @Singleton @Binds fun repository(musicRepository: MusicRepositoryImpl): MusicRepository
@Binds fun settings(musicSettingsImpl: MusicSettingsImpl): MusicSettings @Binds fun settings(musicSettingsImpl: MusicSettingsImpl): MusicSettings
@Binds fun snapshotRestorer(restorer: MusikrSnapshotRestorer): SnapshotRestorer
} }
@@ -246,6 +246,7 @@ constructor(
private val storedPlaylists: StoredPlaylists, private val storedPlaylists: StoredPlaylists,
private val settingCovers: SettingCovers, private val settingCovers: SettingCovers,
private val musicSettings: MusicSettings, private val musicSettings: MusicSettings,
private val snapshotRestorer: SnapshotRestorer,
) : MusicRepository { ) : MusicRepository {
private val updateListeners = mutableListOf<MusicRepository.UpdateListener>() private val updateListeners = mutableListOf<MusicRepository.UpdateListener>()
private val indexingListeners = mutableListOf<MusicRepository.IndexingListener>() private val indexingListeners = mutableListOf<MusicRepository.IndexingListener>()
@@ -257,6 +258,8 @@ constructor(
override val indexingState: IndexingState? override val indexingState: IndexingState?
get() = currentIndexingState ?: previousCompletedState get() = currentIndexingState ?: previousCompletedState
private val snapshotRestoration = snapshotRestorer.start()
@Synchronized @Synchronized
override fun addUpdateListener(listener: MusicRepository.UpdateListener) { override fun addUpdateListener(listener: MusicRepository.UpdateListener) {
L.d("Adding $listener to update listeners") L.d("Adding $listener to update listeners")
@@ -382,6 +385,10 @@ constructor(
private suspend fun indexImpl(withCache: Boolean) { private suspend fun indexImpl(withCache: Boolean) {
L.d("Index requested, initializing") L.d("Index requested, initializing")
val snapshot = snapshotRestoration.await()
if (snapshot != null && !snapshot.empty()) {
emitLibrary(snapshot)
}
// Obtain configuration information // Obtain configuration information
val separators = Separators.from(musicSettings.separators) val separators = Separators.from(musicSettings.separators)
L.d("Separators: $separators") L.d("Separators: $separators")
@@ -433,6 +440,13 @@ constructor(
// Clean up old data that is now impossible for the app to be using. // Clean up old data that is now impossible for the app to be using.
L.d("Cleanup") L.d("Cleanup")
result.cleanup() result.cleanup()
try {
snapshotRestorer.capture(result.library, config)
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
L.w(e, "Library snapshot capture failed")
}
// Finish up loading. // Finish up loading.
L.d("Indexing complete") L.d("Indexing complete")
emitIndexingCompletion(null) emitIndexingCompletion(null)
@@ -35,6 +35,7 @@ import org.oxycblt.auxio.music.MusicSettings
import org.oxycblt.auxio.music.locations.LocationMode import org.oxycblt.auxio.music.locations.LocationMode
import org.oxycblt.auxio.playback.state.PlaybackStateManager import org.oxycblt.auxio.playback.state.PlaybackStateManager
import org.oxycblt.auxio.util.getSystemServiceCompat import org.oxycblt.auxio.util.getSystemServiceCompat
import org.oxycblt.musikr.Library
import org.oxycblt.musikr.MusicParent import org.oxycblt.musikr.MusicParent
import org.oxycblt.musikr.fs.mediastore.MediaStore import org.oxycblt.musikr.fs.mediastore.MediaStore
import org.oxycblt.musikr.fs.saf.SAF import org.oxycblt.musikr.fs.saf.SAF
@@ -155,19 +156,7 @@ private constructor(
L.d("Music changed, updating shared objects") L.d("Music changed, updating shared objects")
// Wipe possibly-invalidated outdated covers // Wipe possibly-invalidated outdated covers
imageLoader.memoryCache?.clear() imageLoader.memoryCache?.clear()
// Clear invalid models from PlaybackStateManager. This is not connected reconcilePlaybackState(playbackManager, library, musicRepository)
// to a listener as it is bad practice for a shared object to attach to
// the listener system of another.
playbackManager.toSavedState()?.let { savedState ->
playbackManager.applySavedState(
savedState.copy(
parent =
savedState.parent?.let { musicRepository.find(it.uid) as? MusicParent? },
heap = savedState.heap.map { song -> song?.let { library.findSong(it.uid) } },
),
true,
)
}
} }
private fun startTracking() { private fun startTracking() {
@@ -232,5 +221,30 @@ private constructor(
companion object { companion object {
const val WAKELOCK_TIMEOUT_MS = 60 * 1000L const val WAKELOCK_TIMEOUT_MS = 60 * 1000L
/** Re-identify saved playback references against the latest published library. */
internal fun reconcilePlaybackState(
playbackManager: PlaybackStateManager,
library: Library,
musicRepository: MusicRepository,
) {
// This is not connected to a listener as it is bad practice for a shared object to
// attach to the listener system of another.
playbackManager.toSavedState()?.let { savedState ->
playbackManager.applySavedState(
savedState.copy(
parent =
savedState.parent?.let {
musicRepository.find(it.uid) as? MusicParent?
},
heap =
savedState.heap.map { song ->
song?.let { library.findSong(it.uid) }
},
),
true,
)
}
}
} }
} }
@@ -167,6 +167,12 @@ class QueueViewModel @Inject constructor(private val playbackManager: PlaybackSt
playbackManager.clearQueue() 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. */ /** Republish the drawer rows from the manager's deck state. */
private fun republish() { private fun republish() {
val rows = listOfNotNull(playbackManager.deckCurrent) + playbackManager.deck val rows = listOfNotNull(playbackManager.deckCurrent) + playbackManager.deck
@@ -287,6 +287,53 @@ class ExoPlaybackStateHolder(
deferSave() deferSave()
} }
override fun shuffleDeck(deckSize: Int, ack: StateAck.ShuffleDeck) {
if (player.currentTimeline.isEmpty || deckSize < 2) {
return
}
val current = player.currentMediaItemIndex
// Walk the play order before touching the timeline: the waiting deck block occupies
// the positions directly behind the current song, and the rest keeps its sequence.
val playOrder = player.unscrambleQueueIndices()
check(playOrder.size >= 1 + deckSize) { "Deck block missing from the timeline" }
val anchor = playOrder[0]
// Extract the block, permute it, and put it back: the physical order is the deck's
// order.
val block =
(current + 1 until current + 1 + deckSize).map {
checkNotNull(player.getMediaItemAt(it).song) { "Untagged media item in the deck block" }
}
player.removeMediaItems(current + 1, current + 1 + deckSize)
player.addMediaItems(current + 1, block.shuffled().map { it.buildMediaItem() })
if (player.shuffleModeEnabled) {
// Re-pin the new deck order after the current song; the rest of the play order
// keeps its sequence. A disturbed order (moves under shuffle leave the shuffle
// order stale) can walk short or with duplicates, so the splice is validated and
// otherwise falls back to repinning the whole order.
val timelineSize = player.mediaItemCount
val rest =
playOrder
.filterNot { it == anchor || it in current + 1..current + deckSize }
.distinct()
val order =
listOf(anchor) + (current + 1 until current + 1 + deckSize).toList() + rest
val valid =
order.size == timelineSize &&
order.all { it in 0 until timelineSize } &&
order.toSet().size == timelineSize
if (valid) {
player.setShuffleOrder(BetterShuffleOrder(order.toIntArray()))
} else {
L.w("Deck shuffle order splice invalid; repinning the whole order")
player.setShuffleOrder(
BetterShuffleOrder.createDeckPinned(timelineSize, anchor, deckSize)
)
}
}
playbackManager.ack(this, ack)
deferSave()
}
override fun next() { override fun next() {
// Replicate the old pseudo-circular queue behavior when no repeat option is implemented. // Replicate the old pseudo-circular queue behavior when no repeat option is implemented.
// Basically, you can't skip back and wrap around the queue, but you can skip forward and // Basically, you can't skip back and wrap around the queue, but you can skip forward and
@@ -145,6 +145,15 @@ interface PlaybackStateHolder {
*/ */
fun shuffled(shuffled: Boolean, deckSize: Int) fun shuffled(shuffled: Boolean, deckSize: Int)
/**
* Randomly reorder the waiting deck songs, which physically occupy the positions directly
* behind the current song.
*
* @param deckSize The number of waiting deck songs to permute.
* @param ack The [StateAck] to return to [PlaybackStateManager].
*/
fun shuffleDeck(deckSize: Int, ack: StateAck.ShuffleDeck)
/** /**
* Handle a deferred playback action. * Handle a deferred playback action.
* *
@@ -206,6 +215,9 @@ sealed interface StateAck {
/** @see PlaybackStateHolder.shuffled */ /** @see PlaybackStateHolder.shuffled */
data object QueueReordered : StateAck data object QueueReordered : StateAck
/** @see PlaybackStateHolder.shuffleDeck */
data object ShuffleDeck : StateAck
/** /**
* @see PlaybackStateHolder.newPlayback * @see PlaybackStateHolder.newPlayback
* @see PlaybackStateHolder.applySavedState * @see PlaybackStateHolder.applySavedState
@@ -204,6 +204,12 @@ interface PlaybackStateManager {
*/ */
fun clearQueue() 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 * 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 * 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 @Synchronized
override fun gotoDeck(row: Int) { override fun gotoDeck(row: Int) {
val stateHolder = stateHolder ?: return 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 -> { is StateAck.NewPlayback -> {
val rawQueue = stateHolder.resolveQueue() val rawQueue = stateHolder.resolveQueue()
stateMirror = stateMirror =
@@ -114,6 +114,14 @@
android:gravity="center_vertical" android:gravity="center_vertical"
android:orientation="horizontal"> 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 <TextView
android:layout_width="0dp" android:layout_width="0dp"
android:layout_height="64dp" android:layout_height="64dp"
+11
View File
@@ -126,6 +126,17 @@
app:layout_constraintEnd_toEndOf="@+id/queue_handle" app:layout_constraintEnd_toEndOf="@+id/queue_handle"
app:layout_constraintStart_toStartOf="parent" /> app:layout_constraintStart_toStartOf="parent" />
<com.google.android.material.button.MaterialButton
android:id="@+id/queue_shuffle"
style="@style/Widget.Auxio.Button.TextButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/lbl_shuffle"
android:visibility="gone"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.google.android.material.button.MaterialButton <com.google.android.material.button.MaterialButton
android:id="@+id/queue_clear" android:id="@+id/queue_clear"
style="@style/Widget.Auxio.Button.TextButton" 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)) 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 @Test
fun `a replacement produces a Replace from the first divergence`() { fun `a replacement produces a Replace from the first divergence`() {
val old = listOf(fakeSong(), fakeSong(), fakeSong()) val old = listOf(fakeSong(), fakeSong(), fakeSong())
@@ -47,6 +47,9 @@ class FakePlaybackStateHolder : PlaybackStateHolder {
/** Every [StateAck.PlayNext] receipt handed to this holder, in order. */ /** Every [StateAck.PlayNext] receipt handed to this holder, in order. */
val insertions = mutableListOf<StateAck.PlayNext>() val insertions = mutableListOf<StateAck.PlayNext>()
/** Every [StateAck.ShuffleDeck] receipt handed to this holder, in order. */
val shuffles = mutableListOf<StateAck.ShuffleDeck>()
var rawQueue = RawQueue.nil() var rawQueue = RawQueue.nil()
private set private set
@@ -225,6 +228,18 @@ class FakePlaybackStateHolder : PlaybackStateHolder {
manager?.ack(this, StateAck.QueueReordered) manager?.ack(this, StateAck.QueueReordered)
} }
override fun shuffleDeck(deckSize: Int, ack: StateAck.ShuffleDeck) {
shuffles += ack
// The waiting deck block directly behind the current song reverses, as a stand-in
// permutation. The playback order pins that block in place, so the resolved order
// follows the new physical order.
val current = rawQueue.heapIndex
val heap = rawQueue.heap.toMutableList()
heap.subList(current + 1, current + 1 + deckSize).reverse()
rawQueue = RawQueue(heap, rawQueue.shuffledMapping, rawQueue.heapIndex)
manager?.ack(this, ack)
}
override fun handleDeferred(action: DeferredPlayback) = false override fun handleDeferred(action: DeferredPlayback) = false
override fun applySavedState( override fun applySavedState(
@@ -242,7 +257,10 @@ class FakePlaybackStateHolder : PlaybackStateHolder {
override fun endSession() {} override fun endSession() {}
override fun reset(ack: StateAck.NewPlayback) {} override fun reset(ack: StateAck.NewPlayback) {
rawQueue = RawQueue.nil()
manager?.ack(this, ack)
}
} }
/** /**
@@ -255,6 +255,58 @@ class PlaybackStateManagerImplTest {
assertEquals(heap[3], manager.currentSong) assertEquals(heap[3], manager.currentSong)
} }
/**
* Shuffle: shuffling the deck permutes the waiting entries in place — the playing row,
* the heap, and the deck size are untouched, and listeners observe the final state.
*/
@Test
fun `shuffleDeck permutes the waiting deck entries in place`() {
val manager = PlaybackStateManagerImpl()
val holder = FakePlaybackStateHolder()
holder.manager = manager
manager.registerStateHolder(holder)
// Record the deck state observed at each callback.
val observedDecks = mutableListOf<List<Song>>()
manager.addListener(
object : PlaybackStateManager.Listener {
override fun onQueueChanged(queue: List<Song>, index: Int, change: QueueChange) {
observedDecks += manager.deck.toList()
}
}
)
// Playing index 2 of a 10-song queue.
val heap = List(10) { fakeSong() }
manager.play(PlaybackCommandFactoryImpl.PlaybackCommandImpl(heap[2], null, heap, false))
// Deck of 3 songs occupies positions 3..5.
val deckBefore = List(3) { fakeSong() }
manager.playAfter(deckBefore)
val queueBefore = manager.queue.toList()
manager.shuffleDeck()
// The holder saw exactly one shuffle receipt.
assertEquals(1, holder.shuffles.size)
// The same waiting entries, possibly reordered: a permutation, not a replacement.
assertEquals(3, manager.deck.size)
assertEquals(deckBefore.map { it.uid }.toSet(), manager.deck.map { it.uid }.toSet())
// The deck mirrors the physical block behind the current song; the heap is untouched.
assertEquals(queueBefore.size, manager.queue.size)
assertEquals(queueBefore.subList(0, 3), manager.queue.subList(0, 3))
assertEquals(queueBefore.subList(6, 13), manager.queue.subList(6, 13))
assertEquals(manager.queue.subList(3, 6).toList(), manager.deck.toList())
// The playing song is heap-sourced here; no playing deck song exists.
assertEquals(null, manager.deckCurrent)
// The callback observed the post-shuffle deck, not a stale one.
assertEquals(manager.deck.toList(), observedDecks.last())
}
/** /**
* Persistence: a deck song missing from the library on restore drops only itself; the * Persistence: a deck song missing from the library on restore drops only itself; the
* rest of the deck survives, matching the heap's own realignment. * rest of the deck survives, matching the heap's own realignment.
+2 -4
View File
@@ -85,12 +85,10 @@ dependencies {
tasks.register("assembleTaglib", Exec, { tasks.register("assembleTaglib", Exec, {
def jniDir = "$projectDir/src/main/cpp" def jniDir = "$projectDir/src/main/cpp"
def libs = new File("$jniDir/taglib/pkg") def libs = new File("$jniDir/taglib/pkg")
if (libs.exists()) {
commandLine "true"
return
}
def ndkDir = androidComponents.sdkComponents.ndkDirectory.get().asFile def ndkDir = androidComponents.sdkComponents.ndkDirectory.get().asFile
commandLine "sh", "-c", "$jniDir/build_taglib.sh $jniDir $ndkDir" commandLine "sh", "-c", "$jniDir/build_taglib.sh $jniDir $ndkDir"
onlyIf { !libs.exists() }
mustRunAfter(tasks.named("clean"))
}) })
afterEvaluate { afterEvaluate {
@@ -19,10 +19,13 @@
package org.oxycblt.musikr package org.oxycblt.musikr
import android.content.Context import android.content.Context
import android.os.SystemClock
import java.util.Collections import java.util.Collections
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import org.oxycblt.musikr.fs.File import org.oxycblt.musikr.fs.File
import org.oxycblt.musikr.pipeline.EvaluateStep import org.oxycblt.musikr.pipeline.EvaluateStep
import org.oxycblt.musikr.pipeline.ExploreStep import org.oxycblt.musikr.pipeline.ExploreStep
@@ -50,7 +53,8 @@ interface Musikr {
* Start loading music using the given config and the configuration provided earlier. * Start loading music using the given config and the configuration provided earlier.
* *
* @param onProgress Optional callback to receive progress on the current status of the music * @param onProgress Optional callback to receive progress on the current status of the music
* pipeline. Warning: These events will be rapid-fire. * pipeline. Intermediate song counts are coalesced, while terminal states are delivered
* promptly.
* @return A handle to the newly created library alongside further cleanup. * @return A handle to the newly created library alongside further cleanup.
*/ */
suspend fun run(onProgress: suspend (IndexingProgress) -> Unit = {}): LibraryResult suspend fun run(onProgress: suspend (IndexingProgress) -> Unit = {}): LibraryResult
@@ -108,6 +112,44 @@ sealed interface IndexingProgress {
data object Indeterminate : IndexingProgress data object Indeterminate : IndexingProgress
} }
/** Coalesces intermediate counts while retaining exact final and terminal progress. */
internal class IndexingProgressCoalescer(
private val intervalMs: Long = 250,
private val clock: () -> Long = SystemClock::elapsedRealtime,
private val onProgress: suspend (IndexingProgress) -> Unit,
) {
private val mutex = Mutex()
private var latestSongs: IndexingProgress.Songs? = null
private var lastEmissionMs: Long? = null
suspend fun submit(progress: IndexingProgress) =
mutex.withLock {
when (progress) {
is IndexingProgress.Songs -> {
latestSongs = progress
val lastEmission = lastEmissionMs
if (lastEmission == null || clock() - lastEmission >= intervalMs) {
flushLatest()
}
}
IndexingProgress.Indeterminate -> {
flushLatest()
onProgress(progress)
lastEmissionMs = clock()
}
}
}
suspend fun flush() = mutex.withLock { flushLatest() }
private suspend fun flushLatest() {
val progress = latestSongs ?: return
onProgress(progress)
latestSongs = null
lastEmissionMs = clock()
}
}
private class MusikrImpl( private class MusikrImpl(
private val config: Config, private val config: Config,
private val exploreStep: ExploreStep, private val exploreStep: ExploreStep,
@@ -115,6 +157,7 @@ private class MusikrImpl(
private val evaluateStep: EvaluateStep, private val evaluateStep: EvaluateStep,
) : Musikr { ) : Musikr {
override suspend fun run(onProgress: suspend (IndexingProgress) -> Unit) = coroutineScope { override suspend fun run(onProgress: suspend (IndexingProgress) -> Unit) = coroutineScope {
val progressCoalescer = IndexingProgressCoalescer(onProgress = onProgress)
onProgress(IndexingProgress.Songs(0, 0)) onProgress(IndexingProgress.Songs(0, 0))
var explored = 0 var explored = 0
var loaded = 0 var loaded = 0
@@ -126,9 +169,10 @@ private class MusikrImpl(
tryAsyncWith(trackedExploredChannel, Dispatchers.Main) { tryAsyncWith(trackedExploredChannel, Dispatchers.Main) {
for (item in exploredChannel) { for (item in exploredChannel) {
explored++ explored++
onProgress(IndexingProgress.Songs(loaded, explored)) progressCoalescer.submit(IndexingProgress.Songs(loaded, explored))
trackedExploredChannel.send(item) trackedExploredChannel.send(item)
} }
progressCoalescer.flush()
} }
val extractedChannel = Channel<Extracted>(Channel.UNLIMITED) val extractedChannel = Channel<Extracted>(Channel.UNLIMITED)
val extractedTask = extractStep.extract(this, trackedExploredChannel, extractedChannel) val extractedTask = extractStep.extract(this, trackedExploredChannel, extractedChannel)
@@ -137,10 +181,11 @@ private class MusikrImpl(
tryAsyncWith(trackedExtractedChannel, Dispatchers.Main) { tryAsyncWith(trackedExtractedChannel, Dispatchers.Main) {
for (item in extractedChannel) { for (item in extractedChannel) {
loaded++ loaded++
onProgress(IndexingProgress.Songs(loaded, explored)) progressCoalescer.submit(IndexingProgress.Songs(loaded, explored))
trackedExtractedChannel.send(item) trackedExtractedChannel.send(item)
} }
onProgress(IndexingProgress.Indeterminate) progressCoalescer.flush()
progressCoalescer.submit(IndexingProgress.Indeterminate)
} }
val library = evaluateStep.evaluate(trackedExtractedChannel, playlistFiles) val library = evaluateStep.evaluate(trackedExtractedChannel, playlistFiles)
merge(exploredTask, extractedTask, trackedExploredTask, trackedExtractedTask).await() merge(exploredTask, extractedTask, trackedExploredTask, trackedExtractedTask).await()
@@ -37,13 +37,16 @@ import org.oxycblt.musikr.tag.parse.ParsedTags
* Create an instance with [from]. * Create an instance with [from].
*/ */
class DBCache private constructor(private val readDao: CacheReadDao) : Cache { class DBCache private constructor(private val readDao: CacheReadDao) : Cache {
private var mapping: Map<Uri, CachedFileData>? = null // The initialized map is immutable, so volatile publication is sufficient for cache hits.
@Volatile private var mapping: Map<Uri, CachedFileData>? = null
private val mappingLock = Mutex() private val mappingLock = Mutex()
override suspend fun read(file: File): CacheResult { override suspend fun read(file: File): CacheResult {
val currentMapping = mappingLock.withLock { val currentMapping =
mapping ?: readDao.selectAllSongs().associateBy { it.uri }.also { mapping = it } mapping
} ?: mappingLock.withLock {
mapping ?: readDao.selectAllSongs().associateBy { it.uri }.also { mapping = it }
}
val dbSong = currentMapping[file.uri] ?: return CacheResult.Miss(file) val dbSong = currentMapping[file.uri] ?: return CacheResult.Miss(file)
if (dbSong.modifiedMs != file.modifiedMs) { if (dbSong.modifiedMs != file.modifiedMs) {
return CacheResult.Stale(file, dbSong.addedMs) 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. * @param context The [Context] to use to access the filesystem and check for ID validity.
*/ */
class FSCovers(private val context: Context) : Covers<FDCover> { class FSCovers(private val context: Context) : Covers<FDCover> {
companion object {
internal fun restore(context: Context, id: String): FDCover? {
if (!id.startsWith(PREFIX)) {
return null
}
return FolderCoverImpl(context, id.substring(PREFIX.length).toUri())
}
}
override suspend fun obtain(id: String): CoverResult<FDCover> { override suspend fun obtain(id: String): CoverResult<FDCover> {
if (!id.startsWith(PREFIX)) { if (!id.startsWith(PREFIX)) {
return CoverResult.Miss() return CoverResult.Miss()
@@ -70,6 +70,8 @@ interface CoverStorage {
suspend fun rm(name: String) suspend fun rm(name: String)
companion object { companion object {
internal fun restore(dir: File, name: String): FDCover = FSStoredCover(File(dir, name))
/** /**
* Create a [CoverStorage] implementation at some directory. Covers will be written in that * Create a [CoverStorage] implementation at some directory. Covers will be written in that
* location. * location.
@@ -40,6 +40,15 @@ private const val PREFIX = "mcs:"
* @param coverStorage The [CoverStorage] to use to obtain the cover data. * @param coverStorage The [CoverStorage] to use to obtain the cover data.
*/ */
class StoredCovers(private val coverStorage: CoverStorage) : Covers<FDCover> { class StoredCovers(private val coverStorage: CoverStorage) : Covers<FDCover> {
companion object {
internal fun restore(id: String, directory: java.io.File): FDCover? {
if (!id.startsWith(PREFIX)) {
return null
}
return StoredCover(CoverStorage.restore(directory, id.substring(PREFIX.length)))
}
}
override suspend fun obtain(id: String): CoverResult<FDCover> { override suspend fun obtain(id: String): CoverResult<FDCover> {
if (!id.startsWith(PREFIX)) { if (!id.startsWith(PREFIX)) {
return CoverResult.Miss() return CoverResult.Miss()
@@ -0,0 +1,63 @@
/*
* Copyright (c) 2026 Auxio Project
* ValueVolumes.kt is part of Auxio.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.oxycblt.musikr.fs.path
import android.content.Context
import org.oxycblt.musikr.fs.Components
import org.oxycblt.musikr.fs.Volume
/** Value-backed internal volume. The display name is not part of its stable identity. */
internal data class InternalVolumeValue(
override val mediaStoreName: String?,
override val components: Components?,
val displayName: String,
) : Volume.Internal {
override fun resolveName(context: Context) = displayName
override fun equals(other: Any?) =
other is InternalVolumeValue &&
mediaStoreName == other.mediaStoreName &&
components == other.components
override fun hashCode() =
31 * (mediaStoreName?.hashCode() ?: 0) + (components?.hashCode() ?: 0)
}
/** Value-backed external volume. The display name is not part of its stable identity. */
internal data class ExternalVolumeValue(
override val id: String?,
override val mediaStoreName: String?,
override val components: Components?,
val displayName: String,
) : Volume.External {
override fun resolveName(context: Context) = displayName
override fun equals(other: Any?) =
other is ExternalVolumeValue &&
id == other.id &&
mediaStoreName == other.mediaStoreName &&
components == other.components
override fun hashCode(): Int {
var result = id?.hashCode() ?: 0
result = 31 * result + (mediaStoreName?.hashCode() ?: 0)
result = 31 * result + (components?.hashCode() ?: 0)
return result
}
}
@@ -42,43 +42,41 @@ internal interface VolumeManager {
companion object { companion object {
fun from(context: Context): VolumeManager = fun from(context: Context): VolumeManager =
VolumeManagerImpl(context.getSystemService(StorageManager::class.java)) VolumeManagerImpl(
context.getSystemService(StorageManager::class.java),
context.applicationContext,
)
} }
} }
private class VolumeManagerImpl(private val storageManager: StorageManager) : VolumeManager { private class VolumeManagerImpl(
private val storageManager: StorageManager,
private val context: Context,
) : VolumeManager {
override fun getInternalVolume(): Volume.Internal = override fun getInternalVolume(): Volume.Internal =
InternalVolumeImpl(storageManager.primaryStorageVolume) storageManager.primaryStorageVolume.toInternalValue(context)
override fun getVolumes() = override fun getVolumes(): List<Volume> =
storageManager.storageVolumesCompat.map { storageManager.storageVolumesCompat.map {
if (it.isInternalCompat) { if (it.isInternalCompat) {
InternalVolumeImpl(it) it.toInternalValue(context)
} else { } else {
ExternalVolumeImpl(it) it.toExternalValue(context)
} }
} }
private data class InternalVolumeImpl(val storageVolume: StorageVolume) : Volume.Internal {
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),
)
@@ -40,7 +40,7 @@ internal interface SongCore {
* @author Alexander Capehart (OxygenCobalt) * @author Alexander Capehart (OxygenCobalt)
*/ */
internal class SongImpl(private val handle: SongCore) : Song { internal class SongImpl(private val handle: SongCore) : Song {
private val preSong = handle.preSong internal val preSong = handle.preSong
override val uid = preSong.v363Uid override val uid = preSong.v363Uid
@@ -0,0 +1,89 @@
/*
* Copyright (c) 2026 Auxio Project
* LibrarySnapshot.kt is part of Auxio.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.oxycblt.musikr.snapshot
import android.content.Context
import java.io.File
import java.io.InputStream
import org.oxycblt.musikr.Config
import org.oxycblt.musikr.Interpretation
import org.oxycblt.musikr.Library
import org.oxycblt.musikr.MutableLibrary
import org.oxycblt.musikr.model.SongImpl
import org.oxycblt.musikr.playlist.db.StoredPlaylists
import org.oxycblt.musikr.playlist.interpret.PlaylistInterpreter
import org.oxycblt.musikr.tag.interpret.PreSong
class LibrarySnapshot
private constructor(
private val context: Context,
private val storedPlaylists: StoredPlaylists,
private val playlistInterpreter: PlaylistInterpreter,
) {
constructor(
context: Context,
config: Config,
) : this(
context,
config.storage.storedPlaylists,
PlaylistInterpreter.new(config.interpretation),
)
constructor(
context: Context,
storedPlaylists: StoredPlaylists,
interpretation: Interpretation,
) : this(context, storedPlaylists, PlaylistInterpreter.new(interpretation))
private val storedCoverDirectory = File(context.filesDir, "covers")
suspend fun capture(
library: Library,
store: LibrarySnapshotStore,
fingerprint: LibrarySnapshotFingerprint,
) {
val songs =
library.songs.map { song ->
(song as? SongImpl)?.preSong
?: throw IllegalArgumentException("Snapshot capture requires Musikr songs")
}
store.replace(
write = { LibrarySnapshotDocument.write(it, songs, fingerprint) },
verify = { read(it, fingerprint) },
)
}
suspend fun restore(
store: LibrarySnapshotStore,
fingerprint: LibrarySnapshotFingerprint,
): MutableLibrary? = store.load { read(it, fingerprint) }
private suspend fun read(
input: InputStream,
fingerprint: LibrarySnapshotFingerprint,
): MutableLibrary =
LibrarySnapshotDocument.read(
input,
fingerprint,
storedCoverDirectory,
context,
storedPlaylists,
playlistInterpreter,
)
}
@@ -0,0 +1,670 @@
/*
* Copyright (c) 2026 Auxio Project
* LibrarySnapshotCodec.kt is part of Auxio.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.oxycblt.musikr.snapshot
import android.content.Context
import android.net.Uri
import java.io.DataInputStream
import java.io.DataOutputStream
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.nio.ByteBuffer
import java.nio.charset.CodingErrorAction
import java.text.Collator
import java.util.UUID
import org.oxycblt.musikr.Music
import org.oxycblt.musikr.fs.Components
import org.oxycblt.musikr.fs.Format
import org.oxycblt.musikr.fs.Path
import org.oxycblt.musikr.fs.Volume
import org.oxycblt.musikr.fs.path.ExternalVolumeValue
import org.oxycblt.musikr.fs.path.InternalVolumeValue
import org.oxycblt.musikr.tag.Date
import org.oxycblt.musikr.tag.Disc
import org.oxycblt.musikr.tag.KnownName
import org.oxycblt.musikr.tag.Name
import org.oxycblt.musikr.tag.Placeholder
import org.oxycblt.musikr.tag.ReleaseType
import org.oxycblt.musikr.tag.ReplayGainAdjustment
import org.oxycblt.musikr.tag.Token
import org.oxycblt.musikr.tag.interpret.PreAlbum
import org.oxycblt.musikr.tag.interpret.PreArtist
import org.oxycblt.musikr.tag.interpret.PreArtistsFrom
import org.oxycblt.musikr.tag.interpret.PreGenre
import org.oxycblt.musikr.tag.interpret.PreSong
object LibrarySnapshotCodec {
const val MAGIC = "AUXSNAP"
private const val SCHEMA_VERSION = 1
private const val MAX_STRING_BYTES = 1024 * 1024
private const val MAX_FORMAT_DEPTH = 8
private const val MAX_NAME_TOKENS = 10_000
private const val MAX_SONG_ARTISTS = 10_000
private const val MAX_SONG_GENRES = 10_000
private val MAGIC_BYTES = MAGIC.toByteArray(Charsets.US_ASCII)
data class Header(val magic: String, val schemaVersion: Int)
data class FileProperties(
val uri: Uri,
val path: Path,
val format: Format,
val size: Long,
val modifiedMs: Long,
val addedMs: Long,
)
fun writeHeader(output: OutputStream) {
val dataOutput = DataOutputStream(output)
dataOutput.write(MAGIC_BYTES)
dataOutput.writeInt(SCHEMA_VERSION)
dataOutput.flush()
}
fun readHeader(input: InputStream): Header {
val dataInput = DataInputStream(input)
val magic = ByteArray(MAGIC_BYTES.size)
dataInput.readFully(magic)
if (!magic.contentEquals(MAGIC_BYTES)) {
throw IOException("Invalid snapshot magic")
}
val schemaVersion = dataInput.readInt()
if (schemaVersion != SCHEMA_VERSION) {
throw IOException("Unsupported snapshot schema version: $schemaVersion")
}
return Header(String(magic, Charsets.US_ASCII), schemaVersion)
}
fun writeString(output: OutputStream, value: String) {
val bytes = value.toByteArray(Charsets.UTF_8)
require(bytes.size <= MAX_STRING_BYTES) { "Snapshot string exceeds byte limit" }
val dataOutput = DataOutputStream(output)
dataOutput.writeInt(bytes.size)
dataOutput.write(bytes)
dataOutput.flush()
}
fun readString(input: InputStream): String {
val dataInput = DataInputStream(input)
val byteCount = dataInput.readInt()
if (byteCount < 0 || byteCount > MAX_STRING_BYTES) {
throw IOException("Invalid snapshot string length: $byteCount")
}
val bytes = ByteArray(byteCount)
dataInput.readFully(bytes)
return Charsets.UTF_8.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT)
.decode(ByteBuffer.wrap(bytes))
.toString()
}
fun writeNullableString(output: OutputStream, value: String?) {
val dataOutput = DataOutputStream(output)
dataOutput.writeBoolean(value != null)
if (value != null) {
writeString(dataOutput, value)
}
dataOutput.flush()
}
fun readNullableString(input: InputStream): String? {
val marker = DataInputStream(input).readUnsignedByte()
return when (marker) {
0 -> null
1 -> readString(input)
else -> throw IOException("Invalid nullable string marker: $marker")
}
}
fun writeInt(output: OutputStream, value: Int) {
val dataOutput = DataOutputStream(output)
dataOutput.writeInt(value)
dataOutput.flush()
}
fun readInt(input: InputStream) = DataInputStream(input).readInt()
fun writeLong(output: OutputStream, value: Long) {
val dataOutput = DataOutputStream(output)
dataOutput.writeLong(value)
dataOutput.flush()
}
fun readLong(input: InputStream) = DataInputStream(input).readLong()
fun writeFloat(output: OutputStream, value: Float) {
val dataOutput = DataOutputStream(output)
dataOutput.writeFloat(value)
dataOutput.flush()
}
fun readFloat(input: InputStream) = DataInputStream(input).readFloat()
fun writeBoolean(output: OutputStream, value: Boolean) {
val dataOutput = DataOutputStream(output)
dataOutput.writeBoolean(value)
dataOutput.flush()
}
fun readBoolean(input: InputStream): Boolean {
val marker = DataInputStream(input).readUnsignedByte()
return when (marker) {
0 -> false
1 -> true
else -> throw IOException("Invalid snapshot boolean marker: $marker")
}
}
fun writeNullableFloat(output: OutputStream, value: Float?) {
val dataOutput = DataOutputStream(output)
dataOutput.writeByte(if (value == null) 0 else 1)
if (value != null) {
writeFloat(dataOutput, value)
}
dataOutput.flush()
}
fun readNullableFloat(input: InputStream): Float? {
val marker = DataInputStream(input).readUnsignedByte()
return when (marker) {
0 -> null
1 -> readFloat(input)
else -> throw IOException("Invalid nullable float marker: $marker")
}
}
fun writeCount(output: OutputStream, value: Int, maximum: Int) {
require(maximum >= 0) { "Snapshot collection maximum must be non-negative" }
require(value >= 0 && value <= maximum) { "Snapshot collection count is out of bounds" }
writeInt(output, value)
}
fun readCount(input: InputStream, maximum: Int): Int {
require(maximum >= 0) { "Snapshot collection maximum must be non-negative" }
val value = readInt(input)
if (value < 0 || value > maximum) {
throw IOException("Invalid snapshot collection count: $value")
}
return value
}
fun writeUid(output: OutputStream, value: Music.UID) {
writeString(output, value.toString())
}
fun readUid(input: InputStream): Music.UID {
val encoded = readString(input)
return Music.UID.fromString(encoded) ?: throw IOException("Invalid snapshot UID")
}
fun writeDate(output: OutputStream, value: Date) {
writeString(output, value.toString())
}
fun readDate(input: InputStream): Date {
val encoded = readString(input)
return Date.from(encoded) ?: throw IOException("Invalid snapshot date")
}
fun writeDisc(output: OutputStream, value: Disc) {
writeInt(output, value.number)
writeNullableString(output, value.name)
}
fun readDisc(input: InputStream): Disc {
return Disc(readInt(input), readNullableString(input))
}
fun writeReleaseType(output: OutputStream, value: ReleaseType) {
when (value) {
is ReleaseType.Album -> {
writeInt(output, 0)
writeNullableString(output, value.refinement?.name)
}
is ReleaseType.EP -> {
writeInt(output, 1)
writeNullableString(output, value.refinement?.name)
}
is ReleaseType.Single -> {
writeInt(output, 2)
writeNullableString(output, value.refinement?.name)
}
is ReleaseType.Compilation -> {
writeInt(output, 3)
writeNullableString(output, value.refinement?.name)
}
ReleaseType.Soundtrack -> writeInt(output, 4)
ReleaseType.Mix -> writeInt(output, 5)
ReleaseType.Mixtape -> writeInt(output, 6)
ReleaseType.Demo -> writeInt(output, 7)
}
}
fun readReleaseType(input: InputStream): ReleaseType {
return when (readInt(input)) {
0 -> ReleaseType.Album(readRefinement(input))
1 -> ReleaseType.EP(readRefinement(input))
2 -> ReleaseType.Single(readRefinement(input))
3 -> ReleaseType.Compilation(readRefinement(input))
4 -> ReleaseType.Soundtrack
5 -> ReleaseType.Mix
6 -> ReleaseType.Mixtape
7 -> ReleaseType.Demo
else -> throw IOException("Invalid snapshot release type")
}
}
private fun readRefinement(input: InputStream): ReleaseType.Refinement? {
return when (readNullableString(input)) {
null -> null
"LIVE" -> ReleaseType.Refinement.LIVE
"REMIX" -> ReleaseType.Refinement.REMIX
else -> throw IOException("Invalid snapshot release refinement")
}
}
fun writeReplayGainAdjustment(output: OutputStream, value: ReplayGainAdjustment) {
writeNullableFloat(output, value.track)
writeNullableFloat(output, value.album)
}
fun readReplayGainAdjustment(input: InputStream): ReplayGainAdjustment {
val track = readNullableFloat(input)
val album = readNullableFloat(input)
return ReplayGainAdjustment(track, album)
}
fun writeMusicBrainzId(output: OutputStream, value: UUID?) {
val dataOutput = DataOutputStream(output)
dataOutput.writeByte(if (value == null) 0 else 1)
if (value != null) {
writeLong(dataOutput, value.mostSignificantBits)
writeLong(dataOutput, value.leastSignificantBits)
}
dataOutput.flush()
}
fun readMusicBrainzId(input: InputStream): UUID? {
val marker = DataInputStream(input).readUnsignedByte()
return when (marker) {
0 -> null
1 -> {
val mostSignificantBits = readLong(input)
val leastSignificantBits = readLong(input)
UUID(mostSignificantBits, leastSignificantBits)
}
else -> throw IOException("Invalid snapshot MusicBrainz ID marker: $marker")
}
}
fun writePath(output: OutputStream, value: Path) {
when (val volume = value.volume) {
is InternalVolumeValue -> {
writeInt(output, 0)
writeNullableString(output, volume.mediaStoreName)
writeNullableString(output, volume.components?.unixString)
writeString(output, volume.displayName)
}
is ExternalVolumeValue -> {
writeInt(output, 1)
writeNullableString(output, volume.id)
writeNullableString(output, volume.mediaStoreName)
writeNullableString(output, volume.components?.unixString)
writeString(output, volume.displayName)
}
else -> throw IOException("Unsupported snapshot path volume")
}
writeString(output, value.components.unixString)
}
fun readPath(input: InputStream): Path {
val volume: Volume =
when (readInt(input)) {
0 -> {
val mediaStoreName = readNullableString(input)
val components = readNullableComponents(input)
InternalVolumeValue(mediaStoreName, components, readString(input))
}
1 -> {
val id = readNullableString(input)
val mediaStoreName = readNullableString(input)
val components = readNullableComponents(input)
ExternalVolumeValue(id, mediaStoreName, components, readString(input))
}
else -> throw IOException("Invalid snapshot path volume")
}
return Path(volume, Components.parseUnix(readString(input)))
}
private fun readNullableComponents(input: InputStream): Components? {
return readNullableString(input)?.let { Components.parseUnix(it) }
}
fun writeUri(output: OutputStream, value: Uri) {
writeString(output, value.toString())
}
fun readUri(input: InputStream): Uri {
return Uri.parse(readString(input))
}
fun writeFormat(output: OutputStream, value: Format) {
writeFormat(output, value, depth = 0)
}
private fun writeFormat(output: OutputStream, value: Format, depth: Int) {
require(depth <= MAX_FORMAT_DEPTH) { "Snapshot format nesting exceeds depth limit" }
when (value) {
Format.MPEG3 -> writeInt(output, 0)
is Format.MPEG4 -> {
writeInt(output, 1)
writeNullableFormat(output, value.containing, depth + 1)
}
Format.AAC -> writeInt(output, 2)
Format.ALAC -> writeInt(output, 3)
is Format.Ogg -> {
writeInt(output, 4)
writeNullableFormat(output, value.containing, depth + 1)
}
Format.Opus -> writeInt(output, 5)
Format.Vorbis -> writeInt(output, 6)
Format.FLAC -> writeInt(output, 7)
Format.Wav -> writeInt(output, 8)
is Format.Unknown -> {
writeInt(output, 9)
writeString(output, value.mimeType)
}
}
}
private fun writeNullableFormat(output: OutputStream, value: Format?, depth: Int) {
writeBoolean(output, value != null)
if (value != null) {
writeFormat(output, value, depth)
}
}
fun readFormat(input: InputStream): Format {
return readFormat(input, depth = 0)
}
private fun readFormat(input: InputStream, depth: Int): Format {
if (depth > MAX_FORMAT_DEPTH) {
throw IOException("Snapshot format nesting exceeds depth limit")
}
return when (readInt(input)) {
0 -> Format.MPEG3
1 -> Format.MPEG4(readNullableFormat(input, depth + 1))
2 -> Format.AAC
3 -> Format.ALAC
4 -> Format.Ogg(readNullableFormat(input, depth + 1))
5 -> Format.Opus
6 -> Format.Vorbis
7 -> Format.FLAC
8 -> Format.Wav
9 -> Format.Unknown(readString(input))
else -> throw IOException("Invalid snapshot audio format")
}
}
private fun readNullableFormat(input: InputStream, depth: Int): Format? {
return if (readBoolean(input)) readFormat(input, depth) else null
}
fun writeFileProperties(output: OutputStream, value: FileProperties) {
writeUri(output, value.uri)
writePath(output, value.path)
writeFormat(output, value.format)
writeLong(output, value.size)
writeLong(output, value.modifiedMs)
writeLong(output, value.addedMs)
}
fun readFileProperties(input: InputStream): FileProperties {
val uri = readUri(input)
val path = readPath(input)
val format = readFormat(input)
val size = readLong(input)
val modifiedMs = readLong(input)
val addedMs = readLong(input)
return FileProperties(uri, path, format, size, modifiedMs, addedMs)
}
fun writeName(output: OutputStream, value: Name) {
when (value) {
is Name.Unknown -> {
writeInt(output, 0)
writeInt(
output,
when (value.placeholder) {
Placeholder.ALBUM -> 0
Placeholder.ARTIST -> 1
Placeholder.GENRE -> 2
},
)
}
is Name.Known -> {
writeInt(output, 1)
writeString(output, value.raw)
writeNullableString(output, value.sort)
writeCount(output, value.tokens.size, MAX_NAME_TOKENS)
for (token in value.tokens) {
writeString(output, token.value)
writeInt(
output,
when (token.type) {
Token.Type.NUMERIC -> 0
Token.Type.LEXICOGRAPHIC -> 1
},
)
}
}
}
}
fun readName(input: InputStream): Name {
return when (readInt(input)) {
0 -> Name.Unknown(readPlaceholder(input))
1 -> readKnownName(input)
else -> throw IOException("Invalid snapshot name")
}
}
private fun readPlaceholder(input: InputStream): Placeholder {
return when (readInt(input)) {
0 -> Placeholder.ALBUM
1 -> Placeholder.ARTIST
2 -> Placeholder.GENRE
else -> throw IOException("Invalid snapshot name placeholder")
}
}
private fun readKnownName(input: InputStream): KnownName {
val raw = readString(input)
val sort = readNullableString(input)
val count = readCount(input, MAX_NAME_TOKENS)
val collator = Collator.getInstance().apply { strength = Collator.PRIMARY }
val tokens =
List(count) {
val value = readString(input)
val type =
when (readInt(input)) {
0 -> Token.Type.NUMERIC
1 -> Token.Type.LEXICOGRAPHIC
else -> throw IOException("Invalid snapshot token type")
}
Token(collator.getCollationKey(value), type)
}
return KnownName(raw, sort, tokens)
}
internal fun writePreSong(output: OutputStream, value: PreSong) {
writeUid(output, value.v363Uid)
writeUid(output, value.v400Uid)
writeUid(output, value.v401Uid)
writeMusicBrainzId(output, value.musicBrainzId)
writeName(output, value.name)
writeString(output, value.rawName)
writeNullableInt(output, value.track)
writeBoolean(output, value.disc != null)
value.disc?.let { writeDisc(output, it) }
writeBoolean(output, value.date != null)
value.date?.let { writeDate(output, it) }
writeFileProperties(
output,
FileProperties(
value.uri,
value.path,
value.format,
value.size,
value.modifiedMs,
value.addedMs,
),
)
writeLong(output, value.durationMs)
writeInt(output, value.bitrateKbps)
writeInt(output, value.sampleRateHz)
writeReplayGainAdjustment(output, value.replayGainAdjustment)
writeNullableString(output, value.cover?.id)
writePreAlbum(output, value.preAlbum)
writePreArtists(output, value.preArtists)
writeCount(output, value.preGenres.size, MAX_SONG_GENRES)
value.preGenres.forEach { writePreGenre(output, it) }
}
internal fun readPreSong(
input: InputStream,
storedCoverDirectory: File,
context: Context,
): PreSong {
val v363Uid = readUid(input)
val v400Uid = readUid(input)
val v401Uid = readUid(input)
val musicBrainzId = readMusicBrainzId(input)
val name = readName(input) as? Name.Known ?: throw IOException("Invalid snapshot song name")
val rawName = readString(input)
val track = readNullableInt(input)
val disc = if (readBoolean(input)) readDisc(input) else null
val date = if (readBoolean(input)) readDate(input) else null
val fileProperties = readFileProperties(input)
val durationMs = readLong(input)
val bitrateKbps = readInt(input)
val sampleRateHz = readInt(input)
val replayGainAdjustment = readReplayGainAdjustment(input)
val coverId = readNullableString(input)
val cover = LibrarySnapshotCovers.restore(coverId, storedCoverDirectory, context)
val preAlbum = readPreAlbum(input)
val preArtists = readPreArtists(input)
val preGenres = List(readCount(input, MAX_SONG_GENRES)) { readPreGenre(input) }
return PreSong(
v363Uid = v363Uid,
v400Uid = v400Uid,
v401Uid = v401Uid,
musicBrainzId = musicBrainzId,
name = name,
rawName = rawName,
track = track,
disc = disc,
date = date,
uri = fileProperties.uri,
path = fileProperties.path,
format = fileProperties.format,
size = fileProperties.size,
durationMs = durationMs,
bitrateKbps = bitrateKbps,
sampleRateHz = sampleRateHz,
replayGainAdjustment = replayGainAdjustment,
modifiedMs = fileProperties.modifiedMs,
addedMs = fileProperties.addedMs,
cover = cover,
preAlbum = preAlbum,
preArtists = preArtists,
preGenres = preGenres,
)
}
private fun writeNullableInt(output: OutputStream, value: Int?) {
writeBoolean(output, value != null)
value?.let { writeInt(output, it) }
}
private fun readNullableInt(input: InputStream): Int? {
return if (readBoolean(input)) readInt(input) else null
}
private fun writePreAlbum(output: OutputStream, value: PreAlbum) {
writeMusicBrainzId(output, value.musicBrainzId)
writeName(output, value.name)
writeNullableString(output, value.rawName)
writeReleaseType(output, value.releaseType)
when (val artists = value.preArtists) {
is PreArtistsFrom.Individual -> {
writeInt(output, 0)
writePreArtists(output, artists.preArtists)
}
is PreArtistsFrom.Album -> {
writeInt(output, 1)
writePreArtists(output, artists.preArtists)
}
}
}
private fun readPreAlbum(input: InputStream): PreAlbum {
val musicBrainzId = readMusicBrainzId(input)
val name = readName(input)
val rawName = readNullableString(input)
val releaseType = readReleaseType(input)
val artistsTag = readInt(input)
val preArtists = readPreArtists(input)
val artists =
when (artistsTag) {
0 -> PreArtistsFrom.Individual(preArtists)
1 -> PreArtistsFrom.Album(preArtists)
else -> throw IOException("Invalid snapshot album artist source")
}
return PreAlbum(musicBrainzId, name, rawName, releaseType, artists)
}
private fun writePreArtists(output: OutputStream, value: List<PreArtist>) {
writeCount(output, value.size, MAX_SONG_ARTISTS)
for (artist in value) {
writeMusicBrainzId(output, artist.musicBrainzId)
writeName(output, artist.name)
writeNullableString(output, artist.rawName)
}
}
private fun readPreArtists(input: InputStream): List<PreArtist> {
return List(readCount(input, MAX_SONG_ARTISTS)) {
PreArtist(readMusicBrainzId(input), readName(input), readNullableString(input))
}
}
private fun writePreGenre(output: OutputStream, value: PreGenre) {
writeName(output, value.name)
writeNullableString(output, value.rawName)
}
private fun readPreGenre(input: InputStream): PreGenre {
return PreGenre(readName(input), readNullableString(input))
}
}
@@ -0,0 +1,32 @@
/*
* Copyright (c) 2026 Auxio Project
* LibrarySnapshotCovers.kt is part of Auxio.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.oxycblt.musikr.snapshot
import android.content.Context
import java.io.File
import org.oxycblt.musikr.covers.FDCover
import org.oxycblt.musikr.covers.fs.FSCovers
import org.oxycblt.musikr.covers.stored.StoredCovers
object LibrarySnapshotCovers {
fun restore(id: String?, storedCoverDirectory: File, context: Context): FDCover? =
id?.let {
StoredCovers.restore(it, storedCoverDirectory) ?: FSCovers.restore(context, it)
}
}
@@ -0,0 +1,82 @@
/*
* Copyright (c) 2026 Auxio Project
* LibrarySnapshotDocument.kt is part of Auxio.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.oxycblt.musikr.snapshot
import android.content.Context
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.util.zip.CRC32
import java.util.zip.CheckedInputStream
import java.util.zip.CheckedOutputStream
import org.oxycblt.musikr.MutableLibrary
import org.oxycblt.musikr.playlist.db.StoredPlaylists
import org.oxycblt.musikr.playlist.interpret.PlaylistInterpreter
import org.oxycblt.musikr.tag.interpret.PreSong
internal object LibrarySnapshotDocument {
private const val MAX_SONGS = 100_000
fun write(
output: OutputStream,
songs: List<PreSong>,
fingerprint: LibrarySnapshotFingerprint,
) {
LibrarySnapshotCodec.writeHeader(output)
val checkedOutput = CheckedOutputStream(output, CRC32())
LibrarySnapshotFingerprintCodec.write(checkedOutput, fingerprint)
LibrarySnapshotCodec.writeCount(checkedOutput, songs.size, MAX_SONGS)
for (song in songs) {
LibrarySnapshotCodec.writePreSong(checkedOutput, song)
}
LibrarySnapshotCodec.writeLong(output, checkedOutput.checksum.value)
}
suspend fun read(
input: InputStream,
expectedFingerprint: LibrarySnapshotFingerprint,
storedCoverDirectory: File,
context: Context,
storedPlaylists: StoredPlaylists,
playlistInterpreter: PlaylistInterpreter,
): MutableLibrary {
LibrarySnapshotCodec.readHeader(input)
val checkedInput = CheckedInputStream(input, CRC32())
val fingerprint = LibrarySnapshotFingerprintCodec.read(checkedInput)
if (fingerprint != expectedFingerprint) {
throw IOException("Snapshot fingerprint mismatch")
}
val songCount = LibrarySnapshotCodec.readCount(checkedInput, MAX_SONGS)
val songs = ArrayList<PreSong>(songCount)
repeat(songCount) {
songs.add(
LibrarySnapshotCodec.readPreSong(checkedInput, storedCoverDirectory, context)
)
}
val expectedChecksum = LibrarySnapshotCodec.readLong(input)
if (checkedInput.checksum.value != expectedChecksum) {
throw IOException("Snapshot checksum mismatch")
}
if (input.read() != -1) {
throw IOException("Trailing snapshot data")
}
return LibrarySnapshotGraph.restore(songs, storedPlaylists, playlistInterpreter)
}
}
@@ -0,0 +1,80 @@
/*
* Copyright (c) 2026 Auxio Project
* LibrarySnapshotFingerprint.kt is part of Auxio.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.oxycblt.musikr.snapshot
import java.io.InputStream
import java.io.OutputStream
data class LibrarySnapshotFingerprint(
val sourceMode: String,
val sourceRoots: List<String>,
val excludedRoots: List<String>,
val withHidden: Boolean,
val excludeNonMusic: Boolean,
val intelligentSorting: Boolean,
val separators: String,
val coverMode: String,
)
internal object LibrarySnapshotFingerprintCodec {
private const val MAX_ROOT_IDENTITIES = 1_000
fun write(output: OutputStream, value: LibrarySnapshotFingerprint) {
LibrarySnapshotCodec.writeString(output, value.sourceMode)
writeStrings(output, value.sourceRoots)
writeStrings(output, value.excludedRoots)
LibrarySnapshotCodec.writeBoolean(output, value.withHidden)
LibrarySnapshotCodec.writeBoolean(output, value.excludeNonMusic)
LibrarySnapshotCodec.writeBoolean(output, value.intelligentSorting)
LibrarySnapshotCodec.writeString(output, value.separators)
LibrarySnapshotCodec.writeString(output, value.coverMode)
}
fun read(input: InputStream): LibrarySnapshotFingerprint {
val sourceMode = LibrarySnapshotCodec.readString(input)
val sourceRoots = readStrings(input)
val excludedRoots = readStrings(input)
val withHidden = LibrarySnapshotCodec.readBoolean(input)
val excludeNonMusic = LibrarySnapshotCodec.readBoolean(input)
val intelligentSorting = LibrarySnapshotCodec.readBoolean(input)
val separators = LibrarySnapshotCodec.readString(input)
val coverMode = LibrarySnapshotCodec.readString(input)
return LibrarySnapshotFingerprint(
sourceMode,
sourceRoots,
excludedRoots,
withHidden,
excludeNonMusic,
intelligentSorting,
separators,
coverMode,
)
}
private fun writeStrings(output: OutputStream, values: List<String>) {
LibrarySnapshotCodec.writeCount(output, values.size, MAX_ROOT_IDENTITIES)
values.forEach { LibrarySnapshotCodec.writeString(output, it) }
}
private fun readStrings(input: InputStream): List<String> {
return List(LibrarySnapshotCodec.readCount(input, MAX_ROOT_IDENTITIES)) {
LibrarySnapshotCodec.readString(input)
}
}
}
@@ -0,0 +1,42 @@
/*
* Copyright (c) 2026 Auxio Project
* LibrarySnapshotGraph.kt is part of Auxio.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.oxycblt.musikr.snapshot
import org.oxycblt.musikr.MutableLibrary
import org.oxycblt.musikr.graph.MusicGraph
import org.oxycblt.musikr.model.LibraryFactory
import org.oxycblt.musikr.playlist.db.StoredPlaylists
import org.oxycblt.musikr.playlist.interpret.PlaylistInterpreter
import org.oxycblt.musikr.tag.interpret.PreSong
internal object LibrarySnapshotGraph {
suspend fun restore(
songs: List<PreSong>,
storedPlaylists: StoredPlaylists,
playlistInterpreter: PlaylistInterpreter,
): MutableLibrary {
val builder = MusicGraph.builder()
songs.forEach { builder.add(it) }
for (file in storedPlaylists.read()) {
builder.add(playlistInterpreter.interpret(file))
}
return LibraryFactory.new()
.create(builder.build(), storedPlaylists, playlistInterpreter)
}
}
@@ -0,0 +1,83 @@
/*
* Copyright (c) 2026 Auxio Project
* LibrarySnapshotStore.kt is part of Auxio.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.oxycblt.musikr.snapshot
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardCopyOption
import kotlin.coroutines.cancellation.CancellationException
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
class LibrarySnapshotStore
internal constructor(
private val directory: File,
private val atomicMove: (Path, Path) -> Unit,
) {
constructor(
directory: File
) : this(
directory,
{ source, target ->
Files.move(
source,
target,
StandardCopyOption.ATOMIC_MOVE,
StandardCopyOption.REPLACE_EXISTING,
)
},
)
private val snapshot = File(directory, "library.snapshot")
suspend fun <T> load(read: suspend (InputStream) -> T): T? {
if (!snapshot.isFile) {
return null
}
return try {
snapshot.inputStream().use { read(it) }
} catch (exception: CancellationException) {
throw exception
} catch (exception: Exception) {
null
}
}
suspend fun replace(
write: suspend (OutputStream) -> Unit,
verify: suspend (InputStream) -> Unit,
) {
if (!directory.isDirectory && !directory.mkdirs() && !directory.isDirectory) {
throw IOException("Unable to create library snapshot directory")
}
val tempFile = File.createTempFile("${snapshot.name}.", ".tmp", directory)
try {
tempFile.outputStream().use { write(it) }
tempFile.inputStream().use { verify(it) }
currentCoroutineContext().ensureActive()
atomicMove(tempFile.toPath(), snapshot.toPath())
} finally {
tempFile.delete()
}
}
}
@@ -70,6 +70,13 @@ sealed interface Name : Comparable<Name> {
} }
} }
/** Shared value implementation used by live naming and snapshot restoration. */
internal data class KnownName(
override val raw: String,
override val sort: String?,
override val tokens: List<Token>,
) : Name.Known()
/** An individual part of a name string that can be compared intelligently. */ /** An individual part of a name string that can be compared intelligently. */
class Token internal constructor(internal val collationKey: CollationKey, internal val type: Type) : class Token internal constructor(internal val collationKey: CollationKey, internal val type: Type) :
Comparable<Token> { Comparable<Token> {
@@ -22,6 +22,8 @@ import android.icu.text.Transliterator
import android.os.Build import android.os.Build
import java.text.CollationKey import java.text.CollationKey
import java.text.Collator import java.text.Collator
import java.util.concurrent.ConcurrentHashMap
import org.oxycblt.musikr.tag.KnownName
import org.oxycblt.musikr.tag.Name import org.oxycblt.musikr.tag.Name
import org.oxycblt.musikr.tag.Placeholder import org.oxycblt.musikr.tag.Placeholder
import org.oxycblt.musikr.tag.Token import org.oxycblt.musikr.tag.Token
@@ -37,105 +39,108 @@ abstract class Naming {
abstract fun name(raw: String, sort: String?): Name.Known abstract fun name(raw: String, sort: String?): Name.Known
companion object { companion object {
fun intelligent(): Naming = IntelligentNaming fun intelligent(): Naming = IntelligentNaming()
fun simple(): Naming = SimpleNaming fun simple(): Naming = SimpleNaming
} }
} }
data object IntelligentNaming : Naming() { class IntelligentNaming(
override fun name(raw: String, sort: String?): Name.Known = IntelligentKnownName(raw, sort) transliteratorFactory: () -> (String) -> String = ::newTransliterator
) : Naming() {
private val tokenCache = ConcurrentHashMap<String, List<Token>>()
private val transliterators =
object : ThreadLocal<(String) -> String>() {
override fun initialValue(): (String) -> String = transliteratorFactory()
}
override fun name(raw: String, sort: String?): Name.Known {
val effectiveName = sort ?: raw
return KnownName(
raw,
sort,
tokenCache.computeIfAbsent(effectiveName) {
parseTokens(it, requireNotNull(transliterators.get()))
},
)
}
} }
data object SimpleNaming : Naming() { data object SimpleNaming : Naming() {
override fun name(raw: String, sort: String?): Name.Known = SimpleKnownName(raw, sort) override fun name(raw: String, sort: String?): Name.Known =
KnownName(raw, sort, simpleTokens(raw, sort))
} }
private val collator: Collator = Collator.getInstance().apply { strength = Collator.PRIMARY } private val collator: Collator = Collator.getInstance().apply { strength = Collator.PRIMARY }
private val punctRegex by lazy { Regex("[\\p{Punct}+]") } private val punctRegex by lazy { Regex("[\\p{Punct}+]") }
private val anyLatinAvailable by lazy {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q &&
Transliterator.getAvailableIDs().toList().contains("Any-Latin")
}
private fun newTransliterator(): (String) -> String {
if (!anyLatinAvailable) return { name -> name }
val transliterator = Transliterator.getInstance("Any-Latin;")
return { name: String -> transliterator.transliterate(name) }
}
// TODO: Consider how you want to handle whitespace and "gaps" in names. // TODO: Consider how you want to handle whitespace and "gaps" in names.
/** private fun parseToken(name: String): Token {
* Plain [Name.Known] implementation that is internationalization-safe. // Remove excess punctuation from the string, as those usually aren't considered in sorting.
* val stripped = name.replace(punctRegex, "").trim().ifEmpty { name }
* @author Alexander Capehart (OxygenCobalt) val collationKey = collator.getCollationKey(stripped)
*/ // Always use lexicographic mode since we aren't parsing any numeric components.
private data class SimpleKnownName(override val raw: String, override val sort: String?) : return Token(collationKey, Token.Type.LEXICOGRAPHIC)
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 simpleTokens(raw: String, sort: String?) = listOf(parseToken(sort ?: raw))
* [Name.Known] implementation that adds advanced sorting behavior at the cost of localization.
*
* @author Alexander Capehart (OxygenCobalt)
*/
private data class IntelligentKnownName(override val raw: String, override val sort: String?) :
Name.Known() {
override val tokens = parseTokens(sort ?: raw)
private fun parseTokens(name: String): List<Token> {
// TODO: This routine is consuming much of the song building runtime, find a way to private val TOKEN_REGEX by lazy { Regex("(\\d+)|(\\D+)") }
// optimize it
var stripped = private fun parseTokens(name: String, transliterate: (String) -> String): List<Token> {
name // TODO: This routine is consuming much of the song building runtime, find a way to
// Replace punctuation with spaces to create token boundaries, improving // optimize it
// sorting of names like "15-9" vs "15-10". var stripped =
.replace(punctRegex, " ") name
.let { it.ifBlank { name } } // Replace punctuation with spaces to create token boundaries, improving
.run { // sorting of names like "15-9" vs "15-10".
// Strip any english articles like "the" or "an" from the start, as music .replace(punctRegex, " ")
// sorting should ignore such when possible. .let { it.ifBlank { name } }
when { .run {
length > 4 && startsWith("the ", ignoreCase = true) -> substring(4) // Strip any english articles like "the" or "an" from the start, as music
length > 3 && startsWith("an ", ignoreCase = true) -> substring(3) // sorting should ignore such when possible.
length > 2 && startsWith("a ", ignoreCase = true) -> substring(2) when {
else -> this 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 { // Transliterate to latin if available
private val TOKEN_REGEX by lazy { Regex("(\\d+)|(\\D+)") } 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)
} }
} }
@@ -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,266 @@
/*
* Copyright (c) 2026 Auxio Project
* LibrarySnapshotCaptureTest.kt is part of Auxio.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.oxycblt.musikr.snapshot
import android.net.Uri
import io.mockk.coEvery
import io.mockk.every
import io.mockk.mockk
import java.io.File
import java.io.IOException
import java.nio.file.AtomicMoveNotSupportedException
import java.nio.file.Files
import kotlin.coroutines.cancellation.CancellationException
import kotlinx.coroutines.Job
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import org.junit.Assert.assertEquals
import org.junit.Assert.assertThrows
import org.junit.Test
import org.junit.runner.RunWith
import org.oxycblt.musikr.Config
import org.oxycblt.musikr.Interpretation
import org.oxycblt.musikr.Library
import org.oxycblt.musikr.Music
import org.oxycblt.musikr.Song
import org.oxycblt.musikr.Storage
import org.oxycblt.musikr.fs.Components
import org.oxycblt.musikr.fs.Format
import org.oxycblt.musikr.fs.Path
import org.oxycblt.musikr.fs.path.InternalVolumeValue
import org.oxycblt.musikr.playlist.PlaylistFile
import org.oxycblt.musikr.playlist.PlaylistHandle
import org.oxycblt.musikr.playlist.SongPointer
import org.oxycblt.musikr.playlist.db.StoredPlaylists
import org.oxycblt.musikr.playlist.interpret.PlaylistInterpreter
import org.oxycblt.musikr.tag.ReleaseType
import org.oxycblt.musikr.tag.ReplayGainAdjustment
import org.oxycblt.musikr.tag.interpret.Naming
import org.oxycblt.musikr.tag.interpret.PreAlbum
import org.oxycblt.musikr.tag.interpret.PreArtist
import org.oxycblt.musikr.tag.interpret.PreArtistsFrom
import org.oxycblt.musikr.tag.interpret.PreGenre
import org.oxycblt.musikr.tag.interpret.PreSong
import org.oxycblt.musikr.tag.interpret.Separators
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config as RobolectricConfig
@RunWith(RobolectricTestRunner::class)
@RobolectricConfig(sdk = [30])
class LibrarySnapshotCaptureTest {
@Test
fun capture_completeLibrary_restoresEquivalentGraph() = runBlocking {
val storedPlaylists = mockk<StoredPlaylists>()
val interpretation = Interpretation(Naming.simple(), Separators.from(""))
val config = Config(mockk(), Storage(mockk(), mockk(), storedPlaylists), interpretation)
val playlistInterpreter = PlaylistInterpreter.new(interpretation)
val input = preSong(91, "Captured")
val handle = TestPlaylistHandle(playlistUid(91))
coEvery { storedPlaylists.read() } returns
listOf(PlaylistFile("Bangers", listOf(SongPointer.UID(input.v363Uid)), handle))
val original =
runBlocking {
LibrarySnapshotGraph.restore(
listOf(input),
storedPlaylists,
playlistInterpreter,
)
}
val directory = Files.createTempDirectory("auxio-capture").toFile().apply { deleteOnExit() }
val store = LibrarySnapshotStore(directory)
val snapshot = LibrarySnapshot(RuntimeEnvironment.getApplication(), config)
val fingerprint = fingerprint()
snapshot.capture(original, store, fingerprint)
val restored = requireNotNull(snapshot.restore(store, fingerprint))
assertEquals(original.songs, restored.songs)
assertEquals(original.albums, restored.albums)
assertEquals(original.artists, restored.artists)
assertEquals(original.genres, restored.genres)
assertEquals(original.playlists, restored.playlists)
assertEquals(listOf("library.snapshot"), directory.listFiles()!!.map { it.name })
}
@Test
fun capture_partialFailureCancellationOrMoveFailure_preservesPreviousValidGraph() =
runBlocking {
val storedPlaylists = mockk<StoredPlaylists>()
val interpretation = Interpretation(Naming.simple(), Separators.from(""))
val config = Config(mockk(), Storage(mockk(), mockk(), storedPlaylists), interpretation)
val playlistInterpreter = PlaylistInterpreter.new(interpretation)
val originalInput = preSong(91, "Captured")
val updatedInput = preSong(91, "Replacement")
val handle = TestPlaylistHandle(playlistUid(91))
val liveFile =
PlaylistFile(
"Bangers",
listOf(SongPointer.UID(originalInput.v363Uid)),
handle,
)
coEvery { storedPlaylists.read() } returns listOf(liveFile)
val original =
LibrarySnapshotGraph.restore(
listOf(originalInput),
storedPlaylists,
playlistInterpreter,
)
val updated =
LibrarySnapshotGraph.restore(
listOf(updatedInput),
storedPlaylists,
playlistInterpreter,
)
val directory =
Files.createTempDirectory("auxio-capture-failure").toFile().apply { deleteOnExit() }
val store = LibrarySnapshotStore(directory)
val snapshot = LibrarySnapshot(RuntimeEnvironment.getApplication(), config)
val fingerprint = fingerprint()
snapshot.capture(original, store, fingerprint)
val partialLibrary = mockk<Library>()
every { partialLibrary.songs } returns listOf(mockk<Song>())
assertSuspendThrows<IllegalArgumentException> {
snapshot.capture(partialLibrary, store, fingerprint)
}
assertPreserved(snapshot, store, fingerprint, original, directory)
coEvery { storedPlaylists.read() } throws IOException("Forced verification failure")
assertSuspendThrows<IOException> {
snapshot.capture(updated, store, fingerprint)
}
coEvery { storedPlaylists.read() } returns listOf(liveFile)
assertPreserved(snapshot, store, fingerprint, original, directory)
val failedMoveStore =
LibrarySnapshotStore(directory) { source, target ->
throw AtomicMoveNotSupportedException(
source.toString(),
target.toString(),
"Forced capture move failure",
)
}
assertSuspendThrows<AtomicMoveNotSupportedException> {
snapshot.capture(updated, failedMoveStore, fingerprint)
}
assertPreserved(snapshot, store, fingerprint, original, directory)
val cancelled = Job().apply { cancel() }
assertSuspendThrows<CancellationException> {
withContext(cancelled) { snapshot.capture(updated, store, fingerprint) }
}
assertPreserved(snapshot, store, fingerprint, original, directory)
}
private inline fun <reified T : Throwable> assertSuspendThrows(
noinline block: suspend () -> Unit
) {
assertThrows(T::class.java) { runBlocking { block() } }
}
private suspend fun assertPreserved(
snapshot: LibrarySnapshot,
store: LibrarySnapshotStore,
fingerprint: LibrarySnapshotFingerprint,
original: Library,
directory: File,
) {
val restored = requireNotNull(snapshot.restore(store, fingerprint))
assertEquals(original.songs, restored.songs)
assertEquals(original.playlists, restored.playlists)
assertEquals(listOf("library.snapshot"), directory.listFiles()!!.map { it.name })
}
private fun fingerprint() =
LibrarySnapshotFingerprint(
sourceMode = "SAF",
sourceRoots = listOf("content://tree/Development/Music"),
excludedRoots = emptyList(),
withHidden = false,
excludeNonMusic = false,
intelligentSorting = true,
separators = ",;",
coverMode = "BALANCED",
)
private fun preSong(suffix: Int, name: String): PreSong {
val artist = PreArtist(null, Naming.simple().name("Artist", null), "Artist")
return PreSong(
v363Uid = songUid(suffix),
v400Uid = songUid(suffix + 1_000),
v401Uid = songUid(suffix + 2_000),
musicBrainzId = null,
name = Naming.simple().name(name, null),
rawName = name,
track = 1,
disc = null,
date = null,
uri = Uri.parse("content://snapshot/${songUid(suffix)}"),
path =
Path(
InternalVolumeValue(
null,
Components.parseUnix("/storage/emulated/0"),
"Internal shared storage",
),
Components.parseUnix("Download/$name.mp3"),
),
format = Format.MPEG3,
size = 1_024L,
durationMs = 60_000L,
bitrateKbps = 128,
sampleRateHz = 44_100,
replayGainAdjustment = ReplayGainAdjustment(null, null),
modifiedMs = 100L,
addedMs = 200L,
cover = null,
preAlbum =
PreAlbum(
null,
Naming.simple().name("Album", null),
"Album",
ReleaseType.Album(null),
PreArtistsFrom.Album(listOf(artist)),
),
preArtists = listOf(artist),
preGenres = listOf(PreGenre(Naming.simple().name("Genre", null), "Genre")),
)
}
private fun songUid(suffix: Int) =
requireNotNull(
Music.UID.fromString("uas00000000-0000-4000-8000-${suffix.toString().padStart(12, '0')}")
)
private fun playlistUid(suffix: Int) =
requireNotNull(
Music.UID.fromString("uap00000000-0000-4000-8000-${suffix.toString().padStart(12, '0')}")
)
private class TestPlaylistHandle(override val uid: Music.UID) : PlaylistHandle {
override suspend fun rename(name: String) {}
override suspend fun add(songs: List<Song>) {}
override suspend fun rewrite(songs: List<Song>) {}
override suspend fun delete() {}
}
}
@@ -0,0 +1,439 @@
/*
* Copyright (c) 2026 Auxio Project
* LibrarySnapshotCodecTest.kt is part of Auxio.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.oxycblt.musikr.snapshot
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.DataOutputStream
import java.io.EOFException
import java.io.IOException
import java.util.UUID
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertThrows
import org.junit.Test
import org.oxycblt.musikr.Music
import org.oxycblt.musikr.fs.Components
import org.oxycblt.musikr.fs.Path
import org.oxycblt.musikr.fs.path.ExternalVolumeValue
import org.oxycblt.musikr.fs.path.InternalVolumeValue
import org.oxycblt.musikr.tag.Date
import org.oxycblt.musikr.tag.Disc
import org.oxycblt.musikr.tag.ReleaseType
import org.oxycblt.musikr.tag.ReplayGainAdjustment
class LibrarySnapshotCodecTest {
@Test
fun header_roundTrip_preservesMagicAndSchemaVersion() {
val output = ByteArrayOutputStream()
LibrarySnapshotCodec.writeHeader(output)
val header = LibrarySnapshotCodec.readHeader(ByteArrayInputStream(output.toByteArray()))
assertEquals(LibrarySnapshotCodec.MAGIC, header.magic)
assertEquals(1, header.schemaVersion)
}
@Test
fun readHeader_unknownMagic_throwsIOException() {
val output = ByteArrayOutputStream()
LibrarySnapshotCodec.writeHeader(output)
val bytes = output.toByteArray()
bytes[0] = 'X'.code.toByte()
assertThrows(IOException::class.java) {
LibrarySnapshotCodec.readHeader(ByteArrayInputStream(bytes))
}
}
@Test
fun readHeader_unknownSchemaVersion_throwsIOException() {
val output = ByteArrayOutputStream()
LibrarySnapshotCodec.writeHeader(output)
val bytes = output.toByteArray()
bytes[bytes.lastIndex] = 2.toByte()
assertThrows(IOException::class.java) {
LibrarySnapshotCodec.readHeader(ByteArrayInputStream(bytes))
}
}
@Test
fun readHeader_truncatedSchemaVersion_throwsEOFException() {
val output = ByteArrayOutputStream()
LibrarySnapshotCodec.writeHeader(output)
val bytes = output.toByteArray()
val truncated = bytes.copyOf(bytes.size - 1)
assertThrows(EOFException::class.java) {
LibrarySnapshotCodec.readHeader(ByteArrayInputStream(truncated))
}
}
@Test
fun string_roundTrip_preservesUtf8Text() {
val value = "Album 初音ミク 🎵"
val output = ByteArrayOutputStream()
LibrarySnapshotCodec.writeString(output, value)
val decoded = LibrarySnapshotCodec.readString(ByteArrayInputStream(output.toByteArray()))
assertEquals(value, decoded)
}
@Test
fun readString_invalidLengths_throwIOException() {
for (byteCount in listOf(-1, 1024 * 1024 + 1)) {
val output = ByteArrayOutputStream()
DataOutputStream(output).writeInt(byteCount)
assertThrows(IOException::class.java) {
LibrarySnapshotCodec.readString(ByteArrayInputStream(output.toByteArray()))
}
}
}
@Test
fun readString_truncatedPayload_throwsEOFException() {
val output = ByteArrayOutputStream()
LibrarySnapshotCodec.writeString(output, "truncated")
val bytes = output.toByteArray()
val truncated = bytes.copyOf(bytes.size - 1)
assertThrows(EOFException::class.java) {
LibrarySnapshotCodec.readString(ByteArrayInputStream(truncated))
}
}
@Test
fun readString_malformedUtf8_throwsIOException() {
val output = ByteArrayOutputStream()
val dataOutput = DataOutputStream(output)
dataOutput.writeInt(1)
dataOutput.writeByte(0x80)
assertThrows(IOException::class.java) {
LibrarySnapshotCodec.readString(ByteArrayInputStream(output.toByteArray()))
}
}
@Test
fun nullableString_roundTrip_distinguishesNullEmptyAndText() {
val output = ByteArrayOutputStream()
LibrarySnapshotCodec.writeNullableString(output, null)
LibrarySnapshotCodec.writeNullableString(output, "")
LibrarySnapshotCodec.writeNullableString(output, "Queue 初音ミク")
val input = ByteArrayInputStream(output.toByteArray())
assertNull(LibrarySnapshotCodec.readNullableString(input))
assertEquals("", LibrarySnapshotCodec.readNullableString(input))
assertEquals("Queue 初音ミク", LibrarySnapshotCodec.readNullableString(input))
}
@Test
fun readNullableString_invalidMarker_throwsIOException() {
val output = ByteArrayOutputStream()
output.write(2)
LibrarySnapshotCodec.writeString(output, "still present")
assertThrows(IOException::class.java) {
LibrarySnapshotCodec.readNullableString(ByteArrayInputStream(output.toByteArray()))
}
}
@Test
fun integer_roundTrip_preservesBoundaries() {
val output = ByteArrayOutputStream()
LibrarySnapshotCodec.writeInt(output, Int.MIN_VALUE)
LibrarySnapshotCodec.writeInt(output, Int.MAX_VALUE)
LibrarySnapshotCodec.writeLong(output, Long.MIN_VALUE)
LibrarySnapshotCodec.writeLong(output, Long.MAX_VALUE)
val input = ByteArrayInputStream(output.toByteArray())
assertEquals(Int.MIN_VALUE, LibrarySnapshotCodec.readInt(input))
assertEquals(Int.MAX_VALUE, LibrarySnapshotCodec.readInt(input))
assertEquals(Long.MIN_VALUE, LibrarySnapshotCodec.readLong(input))
assertEquals(Long.MAX_VALUE, LibrarySnapshotCodec.readLong(input))
}
@Test
fun float_roundTrip_preservesValues() {
val values =
listOf(
0.0f,
-0.0f,
-123.5f,
Float.MIN_VALUE,
Float.MAX_VALUE,
Float.NEGATIVE_INFINITY,
Float.POSITIVE_INFINITY,
Float.NaN,
)
val output = ByteArrayOutputStream()
values.forEach { LibrarySnapshotCodec.writeFloat(output, it) }
val input = ByteArrayInputStream(output.toByteArray())
val decoded = values.map { LibrarySnapshotCodec.readFloat(input) }
assertEquals(values, decoded)
}
@Test
fun boolean_roundTrip_preservesFalseAndTrue() {
val output = ByteArrayOutputStream()
LibrarySnapshotCodec.writeBoolean(output, false)
LibrarySnapshotCodec.writeBoolean(output, true)
val input = ByteArrayInputStream(output.toByteArray())
assertEquals(false, LibrarySnapshotCodec.readBoolean(input))
assertEquals(true, LibrarySnapshotCodec.readBoolean(input))
}
@Test
fun nullableFloat_roundTrip_distinguishesNullAndZero() {
val values = listOf<Float?>(null, 0.0f, -6.5f)
val output = ByteArrayOutputStream()
values.forEach { LibrarySnapshotCodec.writeNullableFloat(output, it) }
val input = ByteArrayInputStream(output.toByteArray())
val decoded = values.map { LibrarySnapshotCodec.readNullableFloat(input) }
assertEquals(values, decoded)
}
@Test
fun primitives_truncatedInput_throwEOFException() {
assertThrows(EOFException::class.java) {
LibrarySnapshotCodec.readInt(ByteArrayInputStream(ByteArray(3)))
}
assertThrows(EOFException::class.java) {
LibrarySnapshotCodec.readLong(ByteArrayInputStream(ByteArray(7)))
}
assertThrows(EOFException::class.java) {
LibrarySnapshotCodec.readFloat(ByteArrayInputStream(ByteArray(3)))
}
assertThrows(EOFException::class.java) {
LibrarySnapshotCodec.readBoolean(ByteArrayInputStream(ByteArray(0)))
}
}
@Test
fun collectionCount_codec_enforcesCallerMaximum() {
val output = ByteArrayOutputStream()
LibrarySnapshotCodec.writeCount(output, 3, maximum = 5)
assertEquals(
3,
LibrarySnapshotCodec.readCount(ByteArrayInputStream(output.toByteArray()), maximum = 5),
)
assertThrows(IllegalArgumentException::class.java) {
LibrarySnapshotCodec.writeCount(ByteArrayOutputStream(), -1, maximum = 5)
}
assertThrows(IllegalArgumentException::class.java) {
LibrarySnapshotCodec.writeCount(ByteArrayOutputStream(), 6, maximum = 5)
}
for (count in listOf(-1, 6)) {
val invalid = ByteArrayOutputStream()
DataOutputStream(invalid).writeInt(count)
assertThrows(IOException::class.java) {
LibrarySnapshotCodec.readCount(
ByteArrayInputStream(invalid.toByteArray()),
maximum = 5,
)
}
}
}
@Test
fun readBoolean_invalidMarker_throwsIOException() {
assertThrows(IOException::class.java) {
LibrarySnapshotCodec.readBoolean(ByteArrayInputStream(byteArrayOf(2)))
}
}
@Test
fun uid_roundTrip_preservesCanonicalRepresentation() {
val uid =
requireNotNull(
Music.UID.fromString("uas00112233-4455-6677-8899-aabbccddeeff")
)
val output = ByteArrayOutputStream()
LibrarySnapshotCodec.writeUid(output, uid)
val decoded = LibrarySnapshotCodec.readUid(ByteArrayInputStream(output.toByteArray()))
assertEquals(uid, decoded)
}
@Test
fun date_roundTrip_preservesFullPrecision() {
val date = requireNotNull(Date.from("2016-08-16T00:01:02Z"))
val output = ByteArrayOutputStream()
LibrarySnapshotCodec.writeDate(output, date)
val decoded = LibrarySnapshotCodec.readDate(ByteArrayInputStream(output.toByteArray()))
assertEquals(date, decoded)
}
@Test
fun disc_roundTrip_preservesNumberAndSubtitle() {
val disc = Disc(2, "Bonus 界")
val output = ByteArrayOutputStream()
LibrarySnapshotCodec.writeDisc(output, disc)
val decoded = LibrarySnapshotCodec.readDisc(ByteArrayInputStream(output.toByteArray()))
assertEquals(disc.number, decoded.number)
assertEquals(disc.name, decoded.name)
}
@Test
fun releaseType_roundTrip_preservesTypeAndRefinement() {
val values =
listOf<ReleaseType>(
ReleaseType.Album(null),
ReleaseType.Album(ReleaseType.Refinement.LIVE),
ReleaseType.EP(ReleaseType.Refinement.REMIX),
ReleaseType.Single(null),
ReleaseType.Compilation(ReleaseType.Refinement.LIVE),
ReleaseType.Soundtrack,
ReleaseType.Mix,
ReleaseType.Mixtape,
ReleaseType.Demo,
)
val output = ByteArrayOutputStream()
values.forEach { LibrarySnapshotCodec.writeReleaseType(output, it) }
val input = ByteArrayInputStream(output.toByteArray())
val decoded = values.map { LibrarySnapshotCodec.readReleaseType(input) }
assertEquals(values, decoded)
}
@Test
fun replayGain_roundTrip_preservesIndependentTrackAndAlbumValues() {
val values =
listOf(
ReplayGainAdjustment(track = -6.5f, album = null),
ReplayGainAdjustment(track = null, album = -9.0f),
)
val output = ByteArrayOutputStream()
values.forEach { LibrarySnapshotCodec.writeReplayGainAdjustment(output, it) }
val input = ByteArrayInputStream(output.toByteArray())
val decoded = values.map { LibrarySnapshotCodec.readReplayGainAdjustment(input) }
assertEquals(values, decoded)
}
@Test
fun musicBrainzId_roundTrip_preservesNullableUuids() {
val values =
listOf<UUID?>(
null,
UUID.fromString("00112233-4455-6677-8899-aabbccddeeff"),
UUID.fromString("ffeeddcc-bbaa-9988-7766-554433221100"),
)
val output = ByteArrayOutputStream()
values.forEach { LibrarySnapshotCodec.writeMusicBrainzId(output, it) }
val input = ByteArrayInputStream(output.toByteArray())
val decoded = values.map { LibrarySnapshotCodec.readMusicBrainzId(input) }
assertEquals(values, decoded)
}
@Test
fun path_roundTrip_preservesSharedVolumesAndComponents() {
val paths =
listOf(
Path(
InternalVolumeValue(
"external_primary",
Components.parseUnix("/storage/emulated/0"),
"Phone",
),
Components.parseUnix("Library/A/song.mp3"),
),
Path(
ExternalVolumeValue(
"7AFE-060A",
"7afe-060a",
Components.parseUnix("/storage/7AFE-060A"),
"SD card",
),
Components.parseUnix("Development/Music/song.mp3"),
),
)
val output = ByteArrayOutputStream()
paths.forEach { LibrarySnapshotCodec.writePath(output, it) }
val input = ByteArrayInputStream(output.toByteArray())
val decoded = paths.map { LibrarySnapshotCodec.readPath(input) }
assertEquals(paths, decoded)
assertEquals("Phone", (decoded[0].volume as InternalVolumeValue).displayName)
assertEquals("SD card", (decoded[1].volume as ExternalVolumeValue).displayName)
}
@Test
fun domainCodecs_invalidEncodings_throwIOException() {
val invalidText = ByteArrayOutputStream()
LibrarySnapshotCodec.writeString(invalidText, "not-a-domain-value")
assertThrows(IOException::class.java) {
LibrarySnapshotCodec.readUid(ByteArrayInputStream(invalidText.toByteArray()))
}
assertThrows(IOException::class.java) {
LibrarySnapshotCodec.readDate(ByteArrayInputStream(invalidText.toByteArray()))
}
fun taggedInput(): ByteArrayInputStream {
val output = ByteArrayOutputStream()
LibrarySnapshotCodec.writeInt(output, 99)
return ByteArrayInputStream(output.toByteArray())
}
assertThrows(IOException::class.java) {
LibrarySnapshotCodec.readReleaseType(taggedInput())
}
assertThrows(IOException::class.java) { LibrarySnapshotCodec.readPath(taggedInput()) }
assertThrows(IOException::class.java) { LibrarySnapshotCodec.readFormat(taggedInput()) }
val invalidRefinement = ByteArrayOutputStream()
LibrarySnapshotCodec.writeInt(invalidRefinement, 0)
LibrarySnapshotCodec.writeNullableString(invalidRefinement, "SYNCHRONIZED")
assertThrows(IOException::class.java) {
LibrarySnapshotCodec.readReleaseType(
ByteArrayInputStream(invalidRefinement.toByteArray())
)
}
val excessiveNesting = ByteArrayOutputStream()
repeat(10) {
LibrarySnapshotCodec.writeInt(excessiveNesting, 1)
LibrarySnapshotCodec.writeBoolean(excessiveNesting, true)
}
assertThrows(IOException::class.java) {
LibrarySnapshotCodec.readFormat(
ByteArrayInputStream(excessiveNesting.toByteArray())
)
}
}
}
@@ -0,0 +1,146 @@
/*
* Copyright (c) 2026 Auxio Project
* LibrarySnapshotCoversTest.kt is part of Auxio.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.oxycblt.musikr.snapshot
import android.net.Uri
import java.io.File
import java.io.FileNotFoundException
import java.nio.file.Files
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.oxycblt.musikr.covers.CoverResult
import org.oxycblt.musikr.covers.fs.FSCovers
import org.oxycblt.musikr.covers.stored.CoverStorage
import org.oxycblt.musikr.covers.stored.StoredCovers
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [30])
class LibrarySnapshotCoversTest {
@Test
fun absentCover_restore_returnsNullWithoutCreatingStorage() {
val root = Files.createTempDirectory("auxio-snapshot-covers").toFile().apply { deleteOnExit() }
val storedCoverDirectory = File(root, "covers")
val context = RuntimeEnvironment.getApplication()
val restored =
LibrarySnapshotCovers.restore(
id = null,
storedCoverDirectory = storedCoverDirectory,
context = context,
)
assertNull(restored)
assertFalse(storedCoverDirectory.exists())
}
@Test
fun storedCover_restore_preservesLiveIdentityEqualityAndHashCode() {
val storedCoverDirectory =
Files.createTempDirectory("auxio-stored-cover").toFile().apply { deleteOnExit() }
File(storedCoverDirectory, "cover.webp").writeBytes(byteArrayOf(1, 2, 3))
val id = "mcs:cover.webp"
val context = RuntimeEnvironment.getApplication()
val live =
runBlocking {
when (val result = StoredCovers(CoverStorage.at(storedCoverDirectory)).obtain(id)) {
is CoverResult.Hit -> result.cover
is CoverResult.Miss -> error("Expected existing stored cover")
}
}
val restored =
requireNotNull(
LibrarySnapshotCovers.restore(
id = id,
storedCoverDirectory = storedCoverDirectory,
context = context,
)
)
assertEquals(id, restored.id)
assertEquals(live, restored)
assertEquals(restored, live)
assertEquals(live.hashCode(), restored.hashCode())
}
@Test
fun folderCover_restoreAfterDeletion_preservesLiveIdentityEqualityAndHashCode() {
val root = Files.createTempDirectory("auxio-folder-cover").toFile().apply { deleteOnExit() }
val storedCoverDirectory = File(root, "covers")
val coverFile = File(root, "folder.jpg").apply { writeBytes(byteArrayOf(4, 5, 6)) }
val id = "mcf:${Uri.fromFile(coverFile)}"
val context = RuntimeEnvironment.getApplication()
val live =
runBlocking {
when (val result = FSCovers(context).obtain(id)) {
is CoverResult.Hit -> result.cover
is CoverResult.Miss -> error("Expected existing folder cover")
}
}
assertTrue(coverFile.delete())
val restored =
requireNotNull(
LibrarySnapshotCovers.restore(
id = id,
storedCoverDirectory = storedCoverDirectory,
context = context,
)
)
assertFalse(coverFile.exists())
assertFalse(storedCoverDirectory.exists())
assertEquals(id, restored.id)
assertEquals(live, restored)
assertEquals(restored, live)
assertEquals(live.hashCode(), restored.hashCode())
}
@Test
fun deletedStoredCover_restore_succeedsAndOpenFailsLazily() {
val storedCoverDirectory =
Files.createTempDirectory("auxio-deleted-cover").toFile().apply { deleteOnExit() }
val coverFile = File(storedCoverDirectory, "deleted.webp")
coverFile.writeBytes(byteArrayOf(7, 8, 9))
assertTrue(coverFile.delete())
val id = "mcs:deleted.webp"
val context = RuntimeEnvironment.getApplication()
val restored =
requireNotNull(
LibrarySnapshotCovers.restore(
id = id,
storedCoverDirectory = storedCoverDirectory,
context = context,
)
)
assertEquals(id, restored.id)
assertThrows(FileNotFoundException::class.java) { runBlocking { restored.open() } }
}
}
@@ -0,0 +1,345 @@
/*
* Copyright (c) 2026 Auxio Project
* LibrarySnapshotDocumentTest.kt is part of Auxio.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.oxycblt.musikr.snapshot
import android.net.Uri
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.every
import io.mockk.mockk
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.EOFException
import java.io.IOException
import java.io.InputStream
import java.nio.file.Files
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Assert.assertSame
import org.junit.Assert.assertThrows
import org.junit.Test
import org.junit.runner.RunWith
import org.oxycblt.musikr.Music
import org.oxycblt.musikr.Song
import org.oxycblt.musikr.fs.Components
import org.oxycblt.musikr.fs.Format
import org.oxycblt.musikr.fs.Path
import org.oxycblt.musikr.fs.path.InternalVolumeValue
import org.oxycblt.musikr.playlist.PlaylistFile
import org.oxycblt.musikr.playlist.PlaylistHandle
import org.oxycblt.musikr.playlist.SongPointer
import org.oxycblt.musikr.playlist.db.StoredPlaylists
import org.oxycblt.musikr.playlist.interpret.PlaylistInterpreter
import org.oxycblt.musikr.playlist.interpret.PrePlaylist
import org.oxycblt.musikr.tag.ReleaseType
import org.oxycblt.musikr.tag.ReplayGainAdjustment
import org.oxycblt.musikr.tag.interpret.Naming
import org.oxycblt.musikr.tag.interpret.PreAlbum
import org.oxycblt.musikr.tag.interpret.PreArtist
import org.oxycblt.musikr.tag.interpret.PreArtistsFrom
import org.oxycblt.musikr.tag.interpret.PreGenre
import org.oxycblt.musikr.tag.interpret.PreSong
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [30])
class LibrarySnapshotDocumentTest {
private companion object {
val TEST_FINGERPRINT =
LibrarySnapshotFingerprint(
"TEST",
emptyList(),
emptyList(),
withHidden = false,
excludeNonMusic = false,
intelligentSorting = true,
separators = "",
coverMode = "AS_IS",
)
}
@Test
fun document_roundTrip_preservesCompleteGraphAndLivePlaylist() {
val storedCoverDirectory =
Files.createTempDirectory("auxio-document-cover").toFile().apply { deleteOnExit() }
val context = RuntimeEnvironment.getApplication()
val cover =
requireNotNull(
LibrarySnapshotCovers.restore("mcs:shared.webp", storedCoverDirectory, context)
)
val first =
preSong(61, "First", albumName = "Shared album", artistName = "Shared artist", genreName = "Shared genre", cover = cover)
val second =
preSong(
62,
"Second",
v400Uid = songUid(162),
albumName = "Shared album",
artistName = "Shared artist",
genreName = "Shared genre",
cover = cover,
)
val third = preSong(63, "Third", albumName = "Other album", artistName = "Other artist", genreName = "Other genre")
val missing = songUid(999)
val handle = TestPlaylistHandle(playlistUid(71))
val file =
PlaylistFile(
"Bangers",
listOf(
SongPointer.UID(third.v363Uid),
SongPointer.UID(first.v400Uid),
SongPointer.UID(missing),
SongPointer.UID(second.v363Uid),
SongPointer.UID(first.v363Uid),
),
handle,
)
val storedPlaylists = mockk<StoredPlaylists>()
coEvery { storedPlaylists.read() } returns listOf(file)
val playlistInterpreter = playlistInterpreter()
val original =
runBlocking {
LibrarySnapshotGraph.restore(
listOf(first, second, third),
storedPlaylists,
playlistInterpreter,
)
}
val output = ByteArrayOutputStream()
LibrarySnapshotDocument.write(output, listOf(first, second, third), TEST_FINGERPRINT)
val restored =
runBlocking {
LibrarySnapshotDocument.read(
ByteArrayInputStream(output.toByteArray()),
TEST_FINGERPRINT,
storedCoverDirectory,
context,
storedPlaylists,
playlistInterpreter,
)
}
val restoredSongs = restored.songs.associateBy { it.uid }
assertEquals(original.songs, restored.songs)
assertEquals(original.albums, restored.albums)
assertEquals(original.artists, restored.artists)
assertEquals(original.genres, restored.genres)
assertEquals(original.playlists, restored.playlists)
assertEquals(2, restored.albums.size)
assertEquals(2, restored.artists.size)
assertEquals(2, restored.genres.size)
assertSame(restoredSongs[first.v363Uid], restored.playlists.single().songs[1])
assertSame(
restoredSongs[third.v363Uid],
restored.playlists.single().songs.first(),
)
}
@Test
fun document_invalidSongCounts_rejectBeforePayloadAllocation() {
val storedCoverDirectory =
Files.createTempDirectory("auxio-invalid-count").toFile().apply { deleteOnExit() }
for (count in listOf(-1, 100_001)) {
val output = ByteArrayOutputStream()
LibrarySnapshotCodec.writeHeader(output)
LibrarySnapshotFingerprintCodec.write(output, TEST_FINGERPRINT)
LibrarySnapshotCodec.writeInt(output, count)
val error =
assertThrows(IOException::class.java) {
readDocument(
ByteArrayInputStream(output.toByteArray()),
storedCoverDirectory,
mockk<StoredPlaylists>(),
mockk<PlaylistInterpreter>(),
)
}
assertEquals("Invalid snapshot collection count: $count", error.message)
}
}
@Test
fun document_corruptionTrailingDataAndTruncation_failBeforeGraphConstruction() {
val storedCoverDirectory =
Files.createTempDirectory("auxio-integrity").toFile().apply { deleteOnExit() }
val song = preSong(81, "Integrity")
val storedPlaylists = mockk<StoredPlaylists>()
coEvery { storedPlaylists.read() } returns emptyList()
val output = ByteArrayOutputStream()
LibrarySnapshotDocument.write(output, listOf(song), TEST_FINGERPRINT)
val bytes = output.toByteArray()
val restored =
readDocument(
ByteArrayInputStream(bytes),
storedCoverDirectory,
storedPlaylists,
playlistInterpreter(),
)
assertEquals(1, restored.songs.size)
val corrupted = bytes.copyOf()
val corruptedIndex = corrupted.lastIndex - 8
corrupted[corruptedIndex] = (corrupted[corruptedIndex].toInt() xor 1).toByte()
val checksumError =
assertThrows(IOException::class.java) {
readDocument(
ByteArrayInputStream(corrupted),
storedCoverDirectory,
storedPlaylists,
playlistInterpreter(),
)
}
assertEquals("Snapshot checksum mismatch", checksumError.message)
val trailingError =
assertThrows(IOException::class.java) {
readDocument(
ByteArrayInputStream(bytes + byteArrayOf(0)),
storedCoverDirectory,
storedPlaylists,
playlistInterpreter(),
)
}
assertEquals("Trailing snapshot data", trailingError.message)
assertThrows(EOFException::class.java) {
readDocument(
ByteArrayInputStream(bytes.copyOf(bytes.size - 9)),
storedCoverDirectory,
storedPlaylists,
playlistInterpreter(),
)
}
assertThrows(EOFException::class.java) {
readDocument(
ByteArrayInputStream(bytes.copyOf(bytes.size - 1)),
storedCoverDirectory,
storedPlaylists,
playlistInterpreter(),
)
}
coVerify(exactly = 1) { storedPlaylists.read() }
}
private fun readDocument(
input: InputStream,
storedCoverDirectory: java.io.File,
storedPlaylists: StoredPlaylists,
playlistInterpreter: PlaylistInterpreter,
) = runBlocking {
LibrarySnapshotDocument.read(
input,
TEST_FINGERPRINT,
storedCoverDirectory,
RuntimeEnvironment.getApplication(),
storedPlaylists,
playlistInterpreter,
)
}
private fun playlistInterpreter(): PlaylistInterpreter {
val interpreter = mockk<PlaylistInterpreter>()
every { interpreter.interpret(any<PlaylistFile>()) } answers {
val file = firstArg<PlaylistFile>()
PrePlaylist(
Naming.simple().name(file.name, null),
file.name,
file.handle,
file.songPointers,
)
}
return interpreter
}
private fun preSong(
suffix: Int,
name: String,
v400Uid: Music.UID = songUid(suffix),
v401Uid: Music.UID = songUid(suffix),
albumName: String = "Album",
artistName: String = "Artist",
genreName: String = "Genre",
cover: org.oxycblt.musikr.covers.Cover? = null,
): PreSong {
val artist = PreArtist(null, Naming.simple().name(artistName, null), artistName)
return PreSong(
v363Uid = songUid(suffix),
v400Uid = v400Uid,
v401Uid = v401Uid,
musicBrainzId = null,
name = Naming.simple().name(name, null),
rawName = name,
track = null,
disc = null,
date = null,
uri = Uri.parse("content://snapshot/${songUid(suffix)}"),
path =
Path(
InternalVolumeValue(
null,
Components.parseUnix("/storage/emulated/0"),
"Internal shared storage",
),
Components.parseUnix("Download/$name.mp3"),
),
format = Format.MPEG3,
size = 1_024L,
durationMs = 60_000L,
bitrateKbps = 128,
sampleRateHz = 44_100,
replayGainAdjustment = ReplayGainAdjustment(null, null),
modifiedMs = 100L,
addedMs = 200L,
cover = cover,
preAlbum =
PreAlbum(
null,
Naming.simple().name(albumName, null),
albumName,
ReleaseType.Album(null),
PreArtistsFrom.Album(listOf(artist)),
),
preArtists = listOf(artist),
preGenres = listOf(PreGenre(Naming.simple().name(genreName, null), genreName)),
)
}
private fun songUid(suffix: Int, format: Char = 'a') =
requireNotNull(
Music.UID.fromString("u${format}s00000000-0000-4000-8000-${suffix.toString().padStart(12, '0')}")
)
private fun playlistUid(suffix: Int) =
requireNotNull(
Music.UID.fromString("uap00000000-0000-4000-8000-${suffix.toString().padStart(12, '0')}")
)
private class TestPlaylistHandle(override val uid: Music.UID) : PlaylistHandle {
override suspend fun rename(name: String) {}
override suspend fun add(songs: List<Song>) {}
override suspend fun rewrite(songs: List<Song>) {}
override suspend fun delete() {}
}
}
@@ -0,0 +1,65 @@
/*
* Copyright (c) 2026 Auxio Project
* LibrarySnapshotFileCodecTest.kt is part of Auxio.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.oxycblt.musikr.snapshot
import android.net.Uri
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.oxycblt.musikr.fs.Components
import org.oxycblt.musikr.fs.Format
import org.oxycblt.musikr.fs.Path
import org.oxycblt.musikr.fs.path.ExternalVolumeValue
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [30])
class LibrarySnapshotFileCodecTest {
@Test
fun fileProperties_roundTrip_preservesIdentitySizeAndTimestamps() {
val value =
LibrarySnapshotCodec.FileProperties(
uri = Uri.parse("content://media/7AFE-060A/audio/media/42"),
path =
Path(
ExternalVolumeValue(
"7AFE-060A",
"7afe-060a",
Components.parseUnix("/storage/7AFE-060A"),
"SD card",
),
Components.parseUnix("Development/Music/Library/song.ogg"),
),
format = Format.Ogg(Format.Opus),
size = 17_130_325L,
modifiedMs = 1_794_589_521_000L,
addedMs = 1_794_619_280_000L,
)
val output = ByteArrayOutputStream()
LibrarySnapshotCodec.writeFileProperties(output, value)
val decoded =
LibrarySnapshotCodec.readFileProperties(ByteArrayInputStream(output.toByteArray()))
assertEquals(value, decoded)
}
}
@@ -0,0 +1,178 @@
/*
* Copyright (c) 2026 Auxio Project
* LibrarySnapshotFingerprintTest.kt is part of Auxio.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.oxycblt.musikr.snapshot
import io.mockk.coEvery
import io.mockk.mockk
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.nio.file.Files
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.oxycblt.musikr.playlist.db.StoredPlaylists
import org.oxycblt.musikr.playlist.interpret.PlaylistInterpreter
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [30])
class LibrarySnapshotFingerprintTest {
@Test
fun matchingFingerprint_documentRestoresSuccessfully() {
val directory = Files.createTempDirectory("auxio-fingerprint-match").toFile().apply { deleteOnExit() }
val fingerprint = fingerprint()
val output = ByteArrayOutputStream()
LibrarySnapshotDocument.write(output, emptyList(), fingerprint)
val restored = readDocument(output.toByteArray(), fingerprint, directory)
assertTrue(restored.empty())
}
@Test
fun sourceModeOrRootChange_isRejectedAsFingerprintMismatch() {
val directory = Files.createTempDirectory("auxio-fingerprint-source").toFile().apply { deleteOnExit() }
val stored = fingerprint()
val output = ByteArrayOutputStream()
LibrarySnapshotDocument.write(output, emptyList(), stored)
val bytes = output.toByteArray()
val changedConfigurations =
listOf(
stored.copy(sourceMode = "MEDIA_STORE"),
stored.copy(sourceRoots = listOf("content://tree/Other")),
stored.copy(excludedRoots = listOf("content://tree/Development/Music/Other")),
)
for (expected in changedConfigurations) {
val error =
assertThrows(IOException::class.java) {
readDocument(bytes, expected, directory)
}
assertEquals("Snapshot fingerprint mismatch", error.message)
}
}
@Test
fun sortingOrSeparatorChange_isRejectedAsFingerprintMismatch() {
val directory = Files.createTempDirectory("auxio-fingerprint-names").toFile().apply { deleteOnExit() }
val stored = fingerprint()
val output = ByteArrayOutputStream()
LibrarySnapshotDocument.write(output, emptyList(), stored)
val bytes = output.toByteArray()
val changedConfigurations =
listOf(
stored.copy(intelligentSorting = false),
stored.copy(separators = ";&"),
)
for (expected in changedConfigurations) {
val error =
assertThrows(IOException::class.java) {
readDocument(bytes, expected, directory)
}
assertEquals("Snapshot fingerprint mismatch", error.message)
}
}
@Test
fun coverModeChange_isRejectedAsFingerprintMismatch() {
val directory = Files.createTempDirectory("auxio-fingerprint-covers").toFile().apply { deleteOnExit() }
val stored = fingerprint()
val output = ByteArrayOutputStream()
LibrarySnapshotDocument.write(output, emptyList(), stored)
val bytes = output.toByteArray()
val changedModes = listOf("OFF", "SAVE_SPACE", "HIGH_QUALITY", "AS_IS")
for (mode in changedModes) {
val error =
assertThrows(IOException::class.java) {
readDocument(bytes, stored.copy(coverMode = mode), directory)
}
assertEquals("Snapshot fingerprint mismatch", error.message)
}
}
@Test
fun mismatchedFingerprint_storeFallsBackAndPreservesUnrelatedCache() = runBlocking {
val root = Files.createTempDirectory("auxio-fingerprint-store").toFile().apply { deleteOnExit() }
val directory = File(root, "snapshots")
val cache = File(root, "tag-cache.db").apply { writeText("preserve-tags") }
val stored = fingerprint()
val store = LibrarySnapshotStore(directory)
store.replace(
write = { LibrarySnapshotDocument.write(it, emptyList(), stored) },
verify = { readStream(it, stored, directory) },
)
val invalid =
store.load {
readStream(it, stored.copy(sourceMode = "MEDIA_STORE"), directory)
}
val valid = store.load { readStream(it, stored, directory) }
assertNull(invalid)
assertEquals("preserve-tags", cache.readText())
assertTrue(valid?.empty() == true)
assertEquals("preserve-tags", cache.readText())
}
private fun readDocument(
bytes: ByteArray,
expectedFingerprint: LibrarySnapshotFingerprint,
directory: File,
) = readStream(ByteArrayInputStream(bytes), expectedFingerprint, directory)
private fun readStream(
input: InputStream,
expectedFingerprint: LibrarySnapshotFingerprint,
directory: File,
) = runBlocking {
val storedPlaylists = mockk<StoredPlaylists>()
coEvery { storedPlaylists.read() } returns emptyList()
LibrarySnapshotDocument.read(
input,
expectedFingerprint,
directory,
RuntimeEnvironment.getApplication(),
storedPlaylists,
mockk<PlaylistInterpreter>(),
)
}
private fun fingerprint() =
LibrarySnapshotFingerprint(
sourceMode = "SAF",
sourceRoots = listOf("content://tree/Development/Music"),
excludedRoots = listOf("content://tree/Development/Music/Excluded"),
withHidden = true,
excludeNonMusic = false,
intelligentSorting = true,
separators = ",;",
coverMode = "BALANCED",
)
}
@@ -0,0 +1,58 @@
/*
* Copyright (c) 2026 Auxio Project
* LibrarySnapshotFormatCodecTest.kt is part of Auxio.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.oxycblt.musikr.snapshot
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.oxycblt.musikr.fs.Format
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [30])
class LibrarySnapshotFormatCodecTest {
@Test
fun format_roundTrip_preservesEveryVariant() {
val values =
listOf(
Format.MPEG3,
Format.MPEG4(Format.AAC),
Format.MPEG4(null),
Format.AAC,
Format.ALAC,
Format.Ogg(Format.Vorbis),
Format.Ogg(null),
Format.Opus,
Format.Vorbis,
Format.FLAC,
Format.Wav,
Format.Unknown("audio/x-custom"),
)
val output = ByteArrayOutputStream()
values.forEach { LibrarySnapshotCodec.writeFormat(output, it) }
val input = ByteArrayInputStream(output.toByteArray())
val decoded = values.map { LibrarySnapshotCodec.readFormat(input) }
assertEquals(values, decoded)
}
}
@@ -0,0 +1,277 @@
/*
* Copyright (c) 2026 Auxio Project
* LibrarySnapshotGraphTest.kt is part of Auxio.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.oxycblt.musikr.snapshot
import android.net.Uri
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import java.nio.file.Files
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Assert.assertSame
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.oxycblt.musikr.Music
import org.oxycblt.musikr.covers.Cover
import org.oxycblt.musikr.fs.Components
import org.oxycblt.musikr.fs.Format
import org.oxycblt.musikr.fs.Path
import org.oxycblt.musikr.fs.path.InternalVolumeValue
import org.oxycblt.musikr.playlist.PlaylistHandle
import org.oxycblt.musikr.playlist.db.StoredPlaylists
import org.oxycblt.musikr.playlist.interpret.PlaylistInterpreter
import org.oxycblt.musikr.playlist.interpret.PostPlaylist
import org.oxycblt.musikr.tag.Name
import org.oxycblt.musikr.tag.ReleaseType
import org.oxycblt.musikr.tag.ReplayGainAdjustment
import org.oxycblt.musikr.tag.interpret.Naming
import org.oxycblt.musikr.tag.interpret.PreAlbum
import org.oxycblt.musikr.tag.interpret.PreArtist
import org.oxycblt.musikr.tag.interpret.PreArtistsFrom
import org.oxycblt.musikr.tag.interpret.PreGenre
import org.oxycblt.musikr.tag.interpret.PreSong
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [30])
class LibrarySnapshotGraphTest {
@Test
fun restore_sharedParentInputs_produceSingleSharedParentObjects() {
val first = preSong("uas00000000-0000-4000-8000-000000000001", "First")
val second = preSong("uas00000000-0000-4000-8000-000000000002", "Second")
val library =
restoreSongs(
listOf(first, second),
mockk<StoredPlaylists>(),
mockk<PlaylistInterpreter>(),
)
val songs = library.songs.associateBy { it.uid }
val firstSong = requireNotNull(songs[first.v363Uid])
val secondSong = requireNotNull(songs[second.v363Uid])
val album = library.albums.single()
val artist = library.artists.single()
val genre = library.genres.single()
assertEquals(2, library.songs.size)
assertSame(album, firstSong.album)
assertSame(album, secondSong.album)
assertSame(artist, firstSong.artists.single())
assertSame(artist, secondSong.artists.single())
assertSame(genre, firstSong.genres.single())
assertSame(genre, secondSong.genres.single())
assertSame(artist, album.artists.single())
assertSame(album, artist.explicitAlbums.single())
assertSame(genre, artist.genres.single())
}
@Test
fun restore_duplicateCurrentUid_keepsFirstRecordWithoutAdditionalParents() {
val uid = "uas00000000-0000-4000-8000-000000000003"
val first = preSong(uid, "First")
val duplicate =
preSong(
uid,
"Replacement",
albumName = "Other album",
artistName = "Other artist",
genreName = "Other genre",
)
val library =
restoreSongs(
listOf(first, duplicate),
mockk<StoredPlaylists>(),
mockk<PlaylistInterpreter>(),
)
val song = library.songs.single()
assertEquals(first.v363Uid, song.uid)
assertEquals("First", song.name.raw)
assertEquals("Album", (song.album.name as Name.Known).raw)
assertEquals("Artist", (song.artists.single().name as Name.Known).raw)
assertEquals("Genre", (song.genres.single().name as Name.Known).raw)
assertEquals(1, library.albums.size)
assertEquals(1, library.artists.size)
assertEquals(1, library.genres.size)
}
@Test
fun restore_findSong_supportsCurrentAndBothCompatibilityUids() {
val value =
preSong(
uid = "uas00000000-0000-4000-8000-000000000004",
name = "Tracked",
v400Uid = "uas00000000-0000-4000-8000-000000000104",
v401Uid = "ums00000000-0000-4000-8000-000000000204",
)
val library =
restoreSongs(
listOf(value),
mockk<StoredPlaylists>(),
mockk<PlaylistInterpreter>(),
)
val song = library.songs.single()
assertSame(song, library.findSong(value.v363Uid))
assertSame(song, library.findSong(value.v400Uid))
assertSame(song, library.findSong(value.v401Uid))
}
@Test
fun restore_coverReferences_preserveSongAndParentImageIdentity() {
val storedCoverDirectory =
Files.createTempDirectory("auxio-graph-cover").toFile().apply { deleteOnExit() }
val cover =
requireNotNull(
LibrarySnapshotCovers.restore(
"mcs:shared.webp",
storedCoverDirectory,
RuntimeEnvironment.getApplication(),
)
)
val library =
restoreSongs(
listOf(
preSong(
"uas00000000-0000-4000-8000-000000000005",
"Illustrated",
cover = cover,
)
),
mockk<StoredPlaylists>(),
mockk<PlaylistInterpreter>(),
)
val song = library.songs.single()
val albumCovers = song.album.covers.covers
val artistCovers = song.artists.single().covers.covers
val genreCovers = song.genres.single().covers.covers
assertSame(cover, song.cover)
assertEquals(1, albumCovers.size)
assertEquals(1, artistCovers.size)
assertEquals(1, genreCovers.size)
assertSame(cover, albumCovers.single())
assertSame(cover, artistCovers.single())
assertSame(cover, genreCovers.single())
}
@Test
fun restoredMutableLibrary_createPlaylist_usesRetainedLiveDependencies() {
val storedPlaylists = mockk<StoredPlaylists>()
val playlistInterpreter = mockk<PlaylistInterpreter>()
val handle = mockk<PlaylistHandle>()
val playlistUid =
requireNotNull(Music.UID.fromString("uap00000000-0000-4000-8000-000000000006"))
every { handle.uid } returns playlistUid
val library =
restoreSongs(
listOf(preSong("uas00000000-0000-4000-8000-000000000006", "Mutable")),
storedPlaylists,
playlistInterpreter,
)
val song = library.songs.single()
coEvery { storedPlaylists.new("Created", listOf(song)) } returns handle
every { playlistInterpreter.interpret("Created", handle) } returns
PostPlaylist(Naming.simple().name("Created", null), "Created", handle)
val updated = runBlocking { library.createPlaylist("Created", listOf(song)) }
val created = updated.playlists.single()
assertTrue(library.playlists.isEmpty())
assertEquals(playlistUid, created.uid)
assertEquals("Created", created.name.raw)
assertSame(song, created.songs.single())
assertSame(created, updated.findPlaylist(playlistUid))
assertSame(created, updated.findPlaylistByName("Created"))
coVerify(exactly = 1) { storedPlaylists.new("Created", listOf(song)) }
verify(exactly = 1) { playlistInterpreter.interpret("Created", handle) }
}
private fun restoreSongs(
songs: List<PreSong>,
storedPlaylists: StoredPlaylists,
playlistInterpreter: PlaylistInterpreter,
) = runBlocking {
coEvery { storedPlaylists.read() } returns emptyList()
LibrarySnapshotGraph.restore(songs, storedPlaylists, playlistInterpreter)
}
private fun preSong(
uid: String,
name: String,
v400Uid: String = uid,
v401Uid: String = uid,
albumName: String = "Album",
artistName: String = "Artist",
genreName: String = "Genre",
cover: Cover? = null,
): PreSong {
val artist =
PreArtist(null, Naming.simple().name(artistName, null), artistName)
return PreSong(
v363Uid = requireNotNull(Music.UID.fromString(uid)),
v400Uid = requireNotNull(Music.UID.fromString(v400Uid)),
v401Uid = requireNotNull(Music.UID.fromString(v401Uid)),
musicBrainzId = null,
name = Naming.simple().name(name, null),
rawName = name,
track = null,
disc = null,
date = null,
uri = Uri.parse("content://snapshot/$uid"),
path =
Path(
InternalVolumeValue(
null,
Components.parseUnix("/storage/emulated/0"),
"Internal shared storage",
),
Components.parseUnix("Download/$name.mp3"),
),
format = Format.MPEG3,
size = 1_024L,
durationMs = 60_000L,
bitrateKbps = 128,
sampleRateHz = 44_100,
replayGainAdjustment = ReplayGainAdjustment(null, null),
modifiedMs = 100L,
addedMs = 200L,
cover = cover,
preAlbum =
PreAlbum(
musicBrainzId = null,
name = Naming.simple().name(albumName, null),
rawName = albumName,
releaseType = ReleaseType.Album(null),
preArtists = PreArtistsFrom.Album(listOf(artist)),
),
preArtists = listOf(artist),
preGenres = listOf(PreGenre(Naming.simple().name(genreName, null), genreName)),
)
}
}
@@ -0,0 +1,168 @@
/*
* Copyright (c) 2026 Auxio Project
* LibrarySnapshotNameCodecTest.kt is part of Auxio.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.oxycblt.musikr.snapshot
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.DataOutputStream
import java.io.IOException
import org.junit.Assert.assertEquals
import org.junit.Assert.assertThrows
import org.junit.Test
import org.oxycblt.musikr.tag.Name
import org.oxycblt.musikr.tag.Placeholder
import org.oxycblt.musikr.tag.Token
import org.oxycblt.musikr.tag.interpret.IntelligentNaming
import org.oxycblt.musikr.tag.interpret.Naming
class LibrarySnapshotNameCodecTest {
@Test
fun unknownName_roundTrip_preservesEveryPlaceholder() {
val values =
listOf(
Name.Unknown(Placeholder.ALBUM),
Name.Unknown(Placeholder.ARTIST),
Name.Unknown(Placeholder.GENRE),
)
val output = ByteArrayOutputStream()
values.forEach { LibrarySnapshotCodec.writeName(output, it) }
val input = ByteArrayInputStream(output.toByteArray())
val decoded = values.map { LibrarySnapshotCodec.readName(input) }
assertEquals(values, decoded)
}
@Test
fun knownName_roundTrip_preservesRawSortAndTokens() {
val value = Naming.simple().name("The Smile", "Smile")
val output = ByteArrayOutputStream()
LibrarySnapshotCodec.writeName(output, value)
val decoded =
LibrarySnapshotCodec.readName(ByteArrayInputStream(output.toByteArray())) as Name.Known
assertEquals(value, decoded)
assertEquals("The Smile", decoded.raw)
assertEquals("Smile", decoded.sort)
assertEquals(listOf("Smile"), decoded.tokens.map { it.value })
}
@Test
fun knownName_numericAndPunctuationTokens_preserveParsedValuesAndTypes() {
val value =
IntelligentNaming(transliteratorFactory = { { input -> input } }).name("15-9", null)
val output = ByteArrayOutputStream()
LibrarySnapshotCodec.writeName(output, value)
val decoded =
LibrarySnapshotCodec.readName(ByteArrayInputStream(output.toByteArray())) as Name.Known
assertEquals(value, decoded)
assertEquals("15-9", decoded.raw)
assertEquals(listOf("15", " ", "9"), decoded.tokens.map { it.value })
assertEquals(
listOf(Token.Type.NUMERIC, Token.Type.LEXICOGRAPHIC, Token.Type.NUMERIC),
decoded.tokens.map { it.type },
)
}
@Test
fun knownName_nonLatinAndLeadingZeroText_preserveRawAndStoredTokens() {
val value =
IntelligentNaming(transliteratorFactory = { { input -> input } })
.name("初音 0032", null)
val output = ByteArrayOutputStream()
LibrarySnapshotCodec.writeName(output, value)
val decoded =
LibrarySnapshotCodec.readName(ByteArrayInputStream(output.toByteArray())) as Name.Known
assertEquals(value, decoded)
assertEquals("初音 0032", decoded.raw)
assertEquals(listOf("初音", "32"), decoded.tokens.map { it.value })
assertEquals(
listOf(Token.Type.LEXICOGRAPHIC, Token.Type.NUMERIC),
decoded.tokens.map { it.type },
)
}
@Test
fun knownName_restoration_reusesStoredTransliterations() {
var transliterations = 0
val value =
IntelligentNaming(
transliteratorFactory = {
{
transliterations += 1
"Hatsune Miku"
}
}
)
.name("初音ミク", null)
assertEquals(1, transliterations)
val output = ByteArrayOutputStream()
LibrarySnapshotCodec.writeName(output, value)
val decoded =
LibrarySnapshotCodec.readName(ByteArrayInputStream(output.toByteArray())) as Name.Known
assertEquals(value, decoded)
assertEquals("Hatsune Miku", decoded.tokens.single().value)
assertEquals(1, transliterations)
}
@Test
fun name_malformedNameAndTokenData_throwIOException() {
val invalidName = ByteArrayOutputStream()
LibrarySnapshotCodec.writeInt(invalidName, 99)
assertThrows(IOException::class.java) {
LibrarySnapshotCodec.readName(ByteArrayInputStream(invalidName.toByteArray()))
}
val invalidPlaceholder = ByteArrayOutputStream()
LibrarySnapshotCodec.writeInt(invalidPlaceholder, 0)
LibrarySnapshotCodec.writeInt(invalidPlaceholder, 99)
assertThrows(IOException::class.java) {
LibrarySnapshotCodec.readName(ByteArrayInputStream(invalidPlaceholder.toByteArray()))
}
for (count in listOf(-1, 10_001)) {
val invalidCount = ByteArrayOutputStream()
LibrarySnapshotCodec.writeInt(invalidCount, 1)
LibrarySnapshotCodec.writeString(invalidCount, "raw")
LibrarySnapshotCodec.writeNullableString(invalidCount, null)
DataOutputStream(invalidCount).writeInt(count)
assertThrows(IOException::class.java) {
LibrarySnapshotCodec.readName(ByteArrayInputStream(invalidCount.toByteArray()))
}
}
val invalidToken = ByteArrayOutputStream()
LibrarySnapshotCodec.writeInt(invalidToken, 1)
LibrarySnapshotCodec.writeString(invalidToken, "raw")
LibrarySnapshotCodec.writeNullableString(invalidToken, null)
LibrarySnapshotCodec.writeCount(invalidToken, 1, maximum = 10_000)
LibrarySnapshotCodec.writeString(invalidToken, "token")
LibrarySnapshotCodec.writeInt(invalidToken, 99)
assertThrows(IOException::class.java) {
LibrarySnapshotCodec.readName(ByteArrayInputStream(invalidToken.toByteArray()))
}
}
}
@@ -0,0 +1,326 @@
/*
* Copyright (c) 2026 Auxio Project
* LibrarySnapshotPlaylistRestoreTest.kt is part of Auxio.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.oxycblt.musikr.snapshot
import android.net.Uri
import io.mockk.Runs
import io.mockk.coEvery
import io.mockk.every
import io.mockk.just
import io.mockk.mockk
import io.mockk.slot
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Assert.assertSame
import org.junit.Test
import org.junit.runner.RunWith
import org.oxycblt.musikr.Music
import org.oxycblt.musikr.Song
import org.oxycblt.musikr.fs.Components
import org.oxycblt.musikr.fs.Format
import org.oxycblt.musikr.fs.Path
import org.oxycblt.musikr.fs.path.InternalVolumeValue
import org.oxycblt.musikr.model.PlaylistImpl
import org.oxycblt.musikr.playlist.PlaylistFile
import org.oxycblt.musikr.playlist.PlaylistHandle
import org.oxycblt.musikr.playlist.PlaylistReconciler
import org.oxycblt.musikr.playlist.SongPointer
import org.oxycblt.musikr.playlist.db.PlaylistDao
import org.oxycblt.musikr.playlist.db.PlaylistInfo
import org.oxycblt.musikr.playlist.db.StoredPlaylistHandle
import org.oxycblt.musikr.playlist.db.StoredPlaylists
import org.oxycblt.musikr.playlist.interpret.PlaylistInterpreter
import org.oxycblt.musikr.playlist.interpret.PostPlaylist
import org.oxycblt.musikr.playlist.interpret.PrePlaylist
import org.oxycblt.musikr.tag.ReleaseType
import org.oxycblt.musikr.tag.ReplayGainAdjustment
import org.oxycblt.musikr.tag.interpret.Naming
import org.oxycblt.musikr.tag.interpret.PreAlbum
import org.oxycblt.musikr.tag.interpret.PreArtist
import org.oxycblt.musikr.tag.interpret.PreArtistsFrom
import org.oxycblt.musikr.tag.interpret.PreGenre
import org.oxycblt.musikr.tag.interpret.PreSong
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [30])
class LibrarySnapshotPlaylistRestoreTest {
@Test
fun restore_preservesLivePlaylistOrderAndRestoredSongLinks() {
val first = preSong("uas00000000-0000-4000-8000-000000000011", "First")
val second = preSong("uas00000000-0000-4000-8000-000000000012", "Second")
val third = preSong("uas00000000-0000-4000-8000-000000000013", "Third")
val handle = TestPlaylistHandle(playlistUid(11))
val storedPlaylists =
InMemoryStoredPlaylists(
listOf(playlistFile("Ordered", listOf(third, first, second), handle))
)
val library = restore(listOf(first, second, third), storedPlaylists)
val playlist = library.playlists.single()
val expected = listOf(third.v363Uid, first.v363Uid, second.v363Uid)
assertEquals(expected, playlist.songs.map { it.uid })
playlist.songs.zip(expected).forEach { (song, uid) ->
assertSame(library.findSong(uid), song)
}
}
@Test
fun restore_duplicatePointers_preserveEvery_PositionAndSongIdentity() {
val first = preSong("uas00000000-0000-4000-8000-000000000021", "First")
val second = preSong("uas00000000-0000-4000-8000-000000000022", "Second")
val handle = TestPlaylistHandle(playlistUid(22))
val storedPlaylists =
InMemoryStoredPlaylists(
listOf(playlistFile("Duplicates", listOf(first, first, second, first), handle))
)
val library = restore(listOf(first, second), storedPlaylists)
val playlist = library.playlists.single()
val restoredFirst = requireNotNull(library.findSong(first.v363Uid))
assertEquals(2, library.songs.size)
assertEquals(4, playlist.songs.size)
assertEquals(
listOf(first.v363Uid, first.v363Uid, second.v363Uid, first.v363Uid),
playlist.songs.map { it.uid },
)
assertSame(restoredFirst, playlist.songs[0])
assertSame(restoredFirst, playlist.songs[1])
assertSame(restoredFirst, playlist.songs[3])
assertSame(library.findSong(second.v363Uid), playlist.songs[2])
}
@Test
fun restore_liveHandle_andRenamePreserveTrackedSourceMetadata() {
val uid = playlistUid(33)
val sourceUri = "content://tree/Playlists/Bangers.m3u"
val dao = mockk<PlaylistDao>()
val updatedInfo = slot<PlaylistInfo>()
coEvery { dao.replacePlaylistInfo(capture(updatedInfo)) } just Runs
val handle =
StoredPlaylistHandle(PlaylistInfo(uid, "Tracked", sourceUri, 42L), dao)
val song = preSong("uas00000000-0000-4000-8000-000000000033", "Tracked song")
val storedPlaylists =
InMemoryStoredPlaylists(listOf(playlistFile("Tracked", listOf(song), handle)))
val library = restore(listOf(song), storedPlaylists)
val playlist = library.playlists.single()
val restoredHandle = (playlist as PlaylistImpl).core.prePlaylist.handle
assertSame(handle, restoredHandle)
val updated = runBlocking { library.renamePlaylist(playlist, "Renamed") }
val updatedHandle = (updated.playlists.single() as PlaylistImpl).core.prePlaylist.handle
assertSame(handle, updatedHandle)
assertEquals(uid, updatedInfo.captured.playlistUid)
assertEquals("Renamed", updatedInfo.captured.name)
assertEquals(sourceUri, updatedInfo.captured.sourceUri)
assertEquals(42L, updatedInfo.captured.sourceSignature)
}
@Test
fun restore_afterStoredPlaylistEdit_usesCurrentDatabaseContent() {
val first = preSong("uas00000000-0000-4000-8000-000000000041", "First")
val second = preSong("uas00000000-0000-4000-8000-000000000042", "Second")
val handle = TestPlaylistHandle(playlistUid(44))
val capturedSongs = listOf(first, second)
val storedPlaylists =
InMemoryStoredPlaylists(
listOf(playlistFile("Bangers", listOf(first, second), handle))
)
val firstLibrary = restore(capturedSongs, storedPlaylists)
storedPlaylists.files = listOf(playlistFile("Edited", listOf(second), handle))
val secondLibrary = restore(capturedSongs, storedPlaylists)
val original = firstLibrary.playlists.single()
val edited = secondLibrary.playlists.single()
assertEquals("Bangers", original.name.raw)
assertEquals(listOf(first.v363Uid, second.v363Uid), original.songs.map { it.uid })
assertEquals("Edited", edited.name.raw)
assertEquals(listOf(second.v363Uid), edited.songs.map { it.uid })
assertSame(secondLibrary.findSong(second.v363Uid), edited.songs.single())
assertSame(handle, (edited as PlaylistImpl).core.prePlaylist.handle)
}
@Test
fun restore_compatibilityAndMissingPointers_resolveNormallyWithoutTruncation() {
val first = preSong("uas00000000-0000-4000-8000-000000000051", "First")
val second =
preSong(
"uas00000000-0000-4000-8000-000000000052",
"Second",
v400Uid = "uas00000000-0000-4000-8000-000000000152",
)
val third =
preSong(
"uas00000000-0000-4000-8000-000000000053",
"Third",
v401Uid = "ums00000000-0000-4000-8000-000000000253",
)
val missing =
requireNotNull(
Music.UID.fromString("uas00000000-0000-4000-8000-000000000999")
)
val file =
PlaylistFile(
"Pointers",
listOf(
SongPointer.UID(first.v363Uid),
SongPointer.UID(second.v400Uid),
SongPointer.UID(missing),
SongPointer.UID(third.v401Uid),
),
TestPlaylistHandle(playlistUid(55)),
)
val library =
restore(listOf(first, second, third), InMemoryStoredPlaylists(listOf(file)))
val playlist = library.playlists.single()
val expected = listOf(first, second, third)
assertEquals(expected.map { it.v363Uid }, playlist.songs.map { it.uid })
expected.zip(playlist.songs).forEach { (input, song) ->
assertSame(library.findSong(input.v363Uid), song)
}
}
private fun restore(
songs: List<PreSong>,
storedPlaylists: StoredPlaylists,
playlistInterpreter: PlaylistInterpreter = playlistInterpreter(),
) = runBlocking {
LibrarySnapshotGraph.restore(songs, storedPlaylists, playlistInterpreter)
}
private fun playlistInterpreter(): PlaylistInterpreter {
val interpreter = mockk<PlaylistInterpreter>()
every { interpreter.interpret(any<PlaylistFile>()) } answers {
val file = firstArg<PlaylistFile>()
PrePlaylist(
Naming.simple().name(file.name, null),
file.name,
file.handle,
file.songPointers,
)
}
every { interpreter.interpret(any<String>(), any<PlaylistHandle>()) } answers {
val name = firstArg<String>()
val handle = secondArg<PlaylistHandle>()
PostPlaylist(Naming.simple().name(name, null), name, handle)
}
return interpreter
}
private fun playlistFile(name: String, songs: List<PreSong>, handle: PlaylistHandle) =
PlaylistFile(name, songs.map { SongPointer.UID(it.v363Uid) }, handle)
private fun playlistUid(suffix: Int) =
requireNotNull(
Music.UID.fromString("uap00000000-0000-4000-8000-${suffix.toString().padStart(12, '0')}")
)
private fun preSong(
uid: String,
name: String,
v400Uid: String = uid,
v401Uid: String = uid,
): PreSong {
val artist = PreArtist(null, Naming.simple().name("Artist", null), "Artist")
return PreSong(
v363Uid = requireNotNull(Music.UID.fromString(uid)),
v400Uid = requireNotNull(Music.UID.fromString(v400Uid)),
v401Uid = requireNotNull(Music.UID.fromString(v401Uid)),
musicBrainzId = null,
name = Naming.simple().name(name, null),
rawName = name,
track = null,
disc = null,
date = null,
uri = Uri.parse("content://snapshot/$uid"),
path =
Path(
InternalVolumeValue(
null,
Components.parseUnix("/storage/emulated/0"),
"Internal shared storage",
),
Components.parseUnix("Download/$name.mp3"),
),
format = Format.MPEG3,
size = 1_024L,
durationMs = 60_000L,
bitrateKbps = 128,
sampleRateHz = 44_100,
replayGainAdjustment = ReplayGainAdjustment(null, null),
modifiedMs = 100L,
addedMs = 200L,
cover = null,
preAlbum =
PreAlbum(
null,
Naming.simple().name("Album", null),
"Album",
ReleaseType.Album(null),
PreArtistsFrom.Album(listOf(artist)),
),
preArtists = listOf(artist),
preGenres = listOf(PreGenre(Naming.simple().name("Genre", null), "Genre")),
)
}
private class TestPlaylistHandle(override val uid: Music.UID) : PlaylistHandle {
override suspend fun rename(name: String) {}
override suspend fun add(songs: List<Song>) {}
override suspend fun rewrite(songs: List<Song>) {}
override suspend fun delete() {}
}
private class InMemoryStoredPlaylists(
var files: List<PlaylistFile>,
var tracked: List<PlaylistReconciler.Tracked> = emptyList(),
) : StoredPlaylists() {
override suspend fun new(name: String, songs: List<Song>): PlaylistHandle =
error("Snapshot restoration must not create playlists")
override suspend fun newTracked(
name: String,
songUids: List<Music.UID>,
sourceUri: String,
sourceSignature: Long,
): PlaylistHandle = error("Snapshot restoration must not create playlists")
override suspend fun replaceTracked(
playlistUid: Music.UID,
name: String,
songUids: List<Music.UID>,
sourceSignature: Long,
) = error("Snapshot restoration must not replace playlists")
override suspend fun readTracked() = tracked
override suspend fun read() = files
}
}
@@ -0,0 +1,235 @@
/*
* Copyright (c) 2026 Auxio Project
* LibrarySnapshotSongCodecTest.kt is part of Auxio.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.oxycblt.musikr.snapshot
import android.net.Uri
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.nio.file.Files
import java.util.UUID
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.oxycblt.musikr.Music
import org.oxycblt.musikr.fs.Components
import org.oxycblt.musikr.fs.Format
import org.oxycblt.musikr.fs.Path
import org.oxycblt.musikr.fs.path.ExternalVolumeValue
import org.oxycblt.musikr.fs.path.InternalVolumeValue
import org.oxycblt.musikr.tag.Date
import org.oxycblt.musikr.tag.Disc
import org.oxycblt.musikr.tag.Name
import org.oxycblt.musikr.tag.Placeholder
import org.oxycblt.musikr.tag.ReleaseType
import org.oxycblt.musikr.tag.ReplayGainAdjustment
import org.oxycblt.musikr.tag.interpret.Naming
import org.oxycblt.musikr.tag.interpret.PreAlbum
import org.oxycblt.musikr.tag.interpret.PreArtist
import org.oxycblt.musikr.tag.interpret.PreArtistsFrom
import org.oxycblt.musikr.tag.interpret.PreGenre
import org.oxycblt.musikr.tag.interpret.PreSong
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [30])
class LibrarySnapshotSongCodecTest {
@Test
fun preSong_roundTrip_preservesEveryCapturedField() {
val storedCoverDirectory =
Files.createTempDirectory("auxio-song-cover").toFile().apply { deleteOnExit() }
val context = RuntimeEnvironment.getApplication()
val value =
PreSong(
v363Uid =
requireNotNull(
Music.UID.fromString("uas00112233-4455-6677-8899-aabbccddeeff")
),
v400Uid =
requireNotNull(
Music.UID.fromString("ums11111111-2222-4333-8444-555566667777")
),
v401Uid =
requireNotNull(
Music.UID.fromString("uas88888888-9999-4aaa-bbbb-ccccddddeeee")
),
musicBrainzId = UUID.fromString("01234567-89ab-4cde-8fab-0123456789ab"),
name = Naming.simple().name("15-9", "nine"),
rawName = "15-9",
track = 9,
disc = Disc(2, "Bonus 界"),
date = requireNotNull(Date.from("2016-08-16T00:01:02Z")),
uri =
Uri.parse(
"content://media/7AFE-060A/audio/media/42/Music/%E5%88%9D%E9%9F%B3.ogg"
),
path =
Path(
ExternalVolumeValue(
"7AFE-060A",
"7afe-060a",
Components.parseUnix("/storage/7AFE-060A"),
"SD card",
),
Components.parseUnix("Development/Music/Library/初音/15-9.ogg"),
),
format = Format.Ogg(Format.Opus),
size = 17_130_325L,
durationMs = 256_008L,
bitrateKbps = 256,
sampleRateHz = 48_000,
replayGainAdjustment = ReplayGainAdjustment(track = -6.5f, album = -9.0f),
modifiedMs = 1_794_589_521_000L,
addedMs = 1_794_619_280_000L,
cover =
requireNotNull(
LibrarySnapshotCovers.restore("mcs:cover.webp", storedCoverDirectory, context)
),
preAlbum =
PreAlbum(
musicBrainzId =
UUID.fromString("12345678-9abc-4def-8123-456789abcdef"),
name = Naming.simple().name("The Silent Force", "Silent Force"),
rawName = "The Silent Force",
releaseType = ReleaseType.Compilation(ReleaseType.Refinement.LIVE),
preArtists =
PreArtistsFrom.Individual(
listOf(
PreArtist(
UUID.fromString(
"abcdef01-2345-4678-9abc-def012345678"
),
Naming.simple().name("初音ミク", "Hatsune Miku"),
"初音ミク",
)
)
),
),
preArtists =
listOf(
PreArtist(
UUID.fromString("abcdef01-2345-4678-9abc-def012345678"),
Naming.simple().name("初音ミク", "Hatsune Miku"),
"初音ミク",
),
PreArtist(null, Naming.simple().name("Within Temptation", null), "Within Temptation"),
),
preGenres =
listOf(
PreGenre(Naming.simple().name("J-pop", null), "J-pop"),
PreGenre(Naming.simple().name("Symphonic 0032", null), "Symphonic 0032"),
),
)
val output = ByteArrayOutputStream()
LibrarySnapshotCodec.writePreSong(output, value)
val decoded =
LibrarySnapshotCodec.readPreSong(
ByteArrayInputStream(output.toByteArray()),
storedCoverDirectory,
context,
)
assertEquals(value, decoded)
assertEquals(value.disc?.name, decoded.disc?.name)
}
@Test
fun preSong_optionalAndCompatibilityFields_roundTripWithoutSubstitutingDefaults() {
val storedCoverDirectory =
Files.createTempDirectory("auxio-optional-song").toFile().apply { deleteOnExit() }
val context = RuntimeEnvironment.getApplication()
val unknownArtist = PreArtist(null, Name.Unknown(Placeholder.ARTIST), null)
val value =
PreSong(
v363Uid =
requireNotNull(
Music.UID.fromString("uas11111111-2222-4333-8444-555566667777")
),
v400Uid =
requireNotNull(
Music.UID.fromString("uas22222222-3333-4444-8555-666677778888")
),
v401Uid =
requireNotNull(
Music.UID.fromString("ums33333333-4444-4555-8666-777788889999")
),
musicBrainzId = null,
name = Naming.simple().name("Loose file", null),
rawName = "Loose file",
track = null,
disc = null,
date = null,
uri = Uri.parse("content://media/internal/audio/media/7"),
path =
Path(
InternalVolumeValue(
null,
Components.parseUnix("/storage/emulated/0"),
"Internal shared storage",
),
Components.parseUnix("Download/Loose file.mp3"),
),
format = Format.MPEG3,
size = 8_192L,
durationMs = 1_000L,
bitrateKbps = 128,
sampleRateHz = 44_100,
replayGainAdjustment = ReplayGainAdjustment(track = null, album = null),
modifiedMs = 0L,
addedMs = 1L,
cover = null,
preAlbum =
PreAlbum(
musicBrainzId = null,
name = Name.Unknown(Placeholder.ALBUM),
rawName = null,
releaseType = ReleaseType.Album(null),
preArtists = PreArtistsFrom.Album(listOf(unknownArtist)),
),
preArtists = listOf(unknownArtist),
preGenres = listOf(PreGenre(Name.Unknown(Placeholder.GENRE), null)),
)
val output = ByteArrayOutputStream()
LibrarySnapshotCodec.writePreSong(output, value)
val decoded =
LibrarySnapshotCodec.readPreSong(
ByteArrayInputStream(output.toByteArray()),
storedCoverDirectory,
context,
)
val decodedUids = listOf(decoded.v363Uid, decoded.v400Uid, decoded.v401Uid)
assertEquals(value, decoded)
assertEquals(listOf(value.v363Uid, value.v400Uid, value.v401Uid), decodedUids)
assertEquals(3, decodedUids.toSet().size)
assertNull(decoded.musicBrainzId)
assertNull(decoded.track)
assertNull(decoded.disc)
assertNull(decoded.date)
assertNull(decoded.cover)
assertNull(decoded.preAlbum.musicBrainzId)
assertNull(decoded.preAlbum.rawName)
assertTrue(decoded.preAlbum.preArtists is PreArtistsFrom.Album)
}
}
@@ -0,0 +1,172 @@
/*
* Copyright (c) 2026 Auxio Project
* LibrarySnapshotStoreTest.kt is part of Auxio.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.oxycblt.musikr.snapshot
import java.io.ByteArrayOutputStream
import java.io.EOFException
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.nio.file.AtomicMoveNotSupportedException
import java.nio.file.Files
import kotlin.coroutines.cancellation.CancellationException
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertThrows
import org.junit.Test
class LibrarySnapshotStoreTest {
@Test
fun load_missingSnapshot_returnsNullWithoutCreatingDirectory() = runBlocking {
val root = Files.createTempDirectory("auxio-store-missing").toFile().apply { deleteOnExit() }
val directory = File(root, "snapshots")
val store = LibrarySnapshotStore(directory)
val result = store.load<String> { error("Absent snapshot must not be decoded") }
assertNull(result)
assertFalse(directory.exists())
}
@Test
fun replace_validSnapshot_verifiesContentsAndCleansTemporaryFiles() = runBlocking {
val directory = Files.createTempDirectory("auxio-store-valid").toFile().apply { deleteOnExit() }
val store = LibrarySnapshotStore(directory)
store.replace(
write = { writeSnapshot(it, "first") },
verify = { assertEquals("first", readSnapshot(it)) },
)
assertEquals("first", store.load(::readSnapshot))
store.replace(
write = { writeSnapshot(it, "second") },
verify = { assertEquals("second", readSnapshot(it)) },
)
assertEquals("second", store.load(::readSnapshot))
assertEquals(listOf("library.snapshot"), directory.listFiles()!!.map { it.name })
}
@Test
fun load_corruptOrTruncatedSnapshot_fallsBackWithoutTouchingOtherFiles() = runBlocking {
val directory = Files.createTempDirectory("auxio-store-invalid").toFile().apply { deleteOnExit() }
val store = LibrarySnapshotStore(directory)
val snapshot = File(directory, "library.snapshot")
val unrelated = File(directory, "unrelated-cache")
unrelated.writeText("preserved")
val valid = ByteArrayOutputStream().also { writeSnapshot(it, "valid") }.toByteArray()
val invalidDocuments =
listOf(
"invalid-magic".toByteArray(),
valid.copyOf(valid.size - 2),
)
for (invalid in invalidDocuments) {
snapshot.writeBytes(invalid)
assertNull(store.load(::readSnapshot))
assertEquals("preserved", unrelated.readText())
}
}
@Test
fun replace_failedWriteVerificationCancellationOrMove_preservesPreviousAndCleansTemps() = runBlocking {
val directory = Files.createTempDirectory("auxio-store-failed").toFile().apply { deleteOnExit() }
val store = LibrarySnapshotStore(directory)
store.replace(
write = { writeSnapshot(it, "stable") },
verify = { assertEquals("stable", readSnapshot(it)) },
)
assertSuspendThrows<IllegalStateException> {
store.replace(
write = {
writeSnapshot(it, "write-failed")
throw IllegalStateException("Forced write failure")
},
verify = { error("Failed write must not be verified") },
)
}
assertEquals("stable", store.load(::readSnapshot))
assertSuspendThrows<CancellationException> {
store.replace(
write = {
writeSnapshot(it, "cancelled")
throw CancellationException("Forced cancellation")
},
verify = { error("Cancelled write must not be verified") },
)
}
assertEquals("stable", store.load(::readSnapshot))
val truncated = ByteArrayOutputStream()
LibrarySnapshotCodec.writeHeader(truncated)
LibrarySnapshotCodec.writeInt(truncated, 10)
truncated.write('v'.code)
assertSuspendThrows<EOFException> {
store.replace(
write = { it.write(truncated.toByteArray()) },
verify = { readSnapshot(it) },
)
}
assertEquals("stable", store.load(::readSnapshot))
val failedMoveStore =
LibrarySnapshotStore(directory) { source, target ->
throw AtomicMoveNotSupportedException(
source.toString(),
target.toString(),
"Forced move failure",
)
}
assertSuspendThrows<AtomicMoveNotSupportedException> {
failedMoveStore.replace(
write = { writeSnapshot(it, "move-failed") },
verify = { assertEquals("move-failed", readSnapshot(it)) },
)
}
assertEquals("stable", store.load(::readSnapshot))
assertEquals(listOf("library.snapshot"), directory.listFiles()!!.map { it.name })
}
private inline fun <reified T : Throwable> assertSuspendThrows(
noinline block: suspend () -> Unit
) {
org.junit.Assert.assertThrows(T::class.java) { runBlocking { block() } }
}
private fun writeSnapshot(output: OutputStream, value: String) {
LibrarySnapshotCodec.writeHeader(output)
LibrarySnapshotCodec.writeString(output, value)
}
private fun readSnapshot(input: InputStream): String {
LibrarySnapshotCodec.readHeader(input)
val value = LibrarySnapshotCodec.readString(input)
if (input.read() != -1) {
throw IOException("Trailing test data")
}
return value
}
}
@@ -0,0 +1,43 @@
/*
* Copyright (c) 2026 Auxio Project
* LibrarySnapshotUriCodecTest.kt is part of Auxio.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.oxycblt.musikr.snapshot
import android.net.Uri
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [30])
class LibrarySnapshotUriCodecTest {
@Test
fun uri_roundTrip_preservesCanonicalText() {
val uri = Uri.parse("content://org.oxycblt.auxio/Library/初音%20ミク.mp3")
val output = ByteArrayOutputStream()
LibrarySnapshotCodec.writeUri(output, uri)
val decoded = LibrarySnapshotCodec.readUri(ByteArrayInputStream(output.toByteArray()))
assertEquals(uri, decoded)
}
}
@@ -18,8 +18,10 @@
package org.oxycblt.musikr.tag.interpret package org.oxycblt.musikr.tag.interpret
import java.util.concurrent.atomic.AtomicInteger
import org.junit.Assert.assertEquals import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotEquals import org.junit.Assert.assertNotEquals
import org.junit.Assert.assertSame
import org.junit.Test import org.junit.Test
import org.oxycblt.musikr.tag.Name import org.oxycblt.musikr.tag.Name
import org.oxycblt.musikr.tag.Placeholder import org.oxycblt.musikr.tag.Placeholder
@@ -302,6 +304,34 @@ class NamingTest {
assertEquals(Token.Type.LEXICOGRAPHIC, only.type) assertEquals(Token.Type.LEXICOGRAPHIC, only.type)
} }
@Test
fun name_intelligent_sameEffectiveName_reusesTokens() {
val naming = Naming.intelligent()
val first = naming.name("The Same", "Same")
val second = naming.name("Same", "Same")
assertSame(first.tokens, second.tokens)
}
@Test
fun name_intelligent_distinctNames_reusesThreadTransliterator() {
val acquisitions = AtomicInteger()
val transliterate = { name: String -> name }
val naming =
IntelligentNaming(
transliteratorFactory = {
acquisitions.incrementAndGet()
transliterate
}
)
naming.name("First name", null)
naming.name("Second name", null)
assertEquals(1, acquisitions.get())
}
@Test @Test
fun name_equals_simple() { fun name_equals_simple() {
val a = Naming.simple().name("The Same", "Same") val a = Naming.simple().name("The Same", "Same")