From 22ee5b2698ab021dd78d030e050c58b0aa390190 Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Sun, 1 Jun 2025 09:12:24 -0600 Subject: [PATCH 1/5] musikr.fs: stream in file tree cache --- .../java/org/oxycblt/musikr/fs/device/FileTreeCache.kt | 9 ++++----- .../main/java/org/oxycblt/musikr/fs/device/QueryUtil.kt | 2 +- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/FileTreeCache.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/FileTreeCache.kt index e8d71bbd1..210f8d4a5 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/FileTreeCache.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/FileTreeCache.kt @@ -28,6 +28,8 @@ import kotlinx.serialization.Serializable import kotlinx.serialization.decodeFromString import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json +import kotlinx.serialization.json.decodeFromStream +import kotlinx.serialization.json.encodeToStream interface FileTreeCache { fun read(): FileTree @@ -94,8 +96,7 @@ private class FileTreeCacheImpl(private val context: Context) : FileTreeCache { return if (cacheFile.exists()) { try { - val jsonContent = cacheFile.readText() - val fileTreeCache = json.decodeFromString(jsonContent) + val fileTreeCache = json.decodeFromStream(cacheFile.inputStream()) FileTreeImpl( context, fileTreeCache.directories.toMutableMap(), @@ -153,9 +154,7 @@ private class FileTreeImpl( val fileTreeCache = FileTreeData( directories = mutableDirectories.toMap(), files = mutableFiles.toMap()) - - val jsonContent = json.encodeToString(fileTreeCache) - cacheFile.writeText(jsonContent) + json.encodeToStream(fileTreeCache, cacheFile.outputStream()) Log.d(TAG, "Successfully wrote cache to disk") } catch (e: Exception) { Log.e(TAG, "Failed to write cache file", e) diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/QueryUtil.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/QueryUtil.kt index a2dfbc041..15324c150 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/QueryUtil.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/QueryUtil.kt @@ -74,4 +74,4 @@ internal inline fun ContentResolver.useQuery( args: Array? = null, sortOrder: String? = null, block: (Cursor) -> R -) = safeQuery(uri, projection, selector, args, sortOrder).use(block) +) = query(uri, projection, selector, args, sortOrder)?.use(block) From 078718fadbe59b54c9cc670ff4980fc428a2be97 Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Sun, 1 Jun 2025 19:33:13 -0600 Subject: [PATCH 2/5] musikr: implement contentresolver ratelimits 1000 queries per second is probably slower than the prior max speed but is sadly required. --- .../org/oxycblt/musikr/fs/device/DeviceFS.kt | 5 +- .../oxycblt/musikr/fs/device/FileTreeCache.kt | 2 - .../org/oxycblt/musikr/fs/device/QueryUtil.kt | 11 +- .../fs/device/RateLimitedContentResolver.kt | 121 ++++++++++++++++++ 4 files changed, 133 insertions(+), 6 deletions(-) create mode 100644 musikr/src/main/java/org/oxycblt/musikr/fs/device/RateLimitedContentResolver.kt diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt index 55e36ecce..07a4b0796 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt @@ -18,7 +18,6 @@ package org.oxycblt.musikr.fs.device -import android.content.ContentResolver import android.content.Context import android.net.Uri import android.provider.DocumentsContract @@ -52,12 +51,12 @@ internal interface DeviceFS { companion object { fun from(context: Context, withHidden: Boolean): DeviceFS = - DeviceFSImpl(context.contentResolverSafe, withHidden) + DeviceFSImpl(context.rateLimitedContentResolver, withHidden) } } private class DeviceFSImpl( - private val contentResolver: ContentResolver, + private val contentResolver: RateLimitedContentResolver, private val withHidden: Boolean ) : DeviceFS { private val explorationScope = CoroutineScope(Dispatchers.IO + SupervisorJob()) diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/FileTreeCache.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/FileTreeCache.kt index 210f8d4a5..c33b8efcb 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/FileTreeCache.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/FileTreeCache.kt @@ -25,8 +25,6 @@ import java.io.File import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import kotlinx.serialization.Serializable -import kotlinx.serialization.decodeFromString -import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import kotlinx.serialization.json.decodeFromStream import kotlinx.serialization.json.encodeToStream diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/QueryUtil.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/QueryUtil.kt index 15324c150..c1736e8db 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/QueryUtil.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/QueryUtil.kt @@ -30,6 +30,15 @@ import android.net.Uri internal val Context.contentResolverSafe: ContentResolver get() = applicationContext.contentResolver +internal val Context.rateLimitedContentResolver: RateLimitedContentResolver + get() = + RateLimitedContentResolver( + contentResolver = contentResolverSafe, + maxTokens = 100, // Maximum burst capacity + refillRate = 1000.0, // 1000 queries per second (100 queries per 100ms) + maxConcurrency = 10 // Maximum concurrent queries + ) + /** * A shortcut for querying the [ContentResolver] database. * @@ -74,4 +83,4 @@ internal inline fun ContentResolver.useQuery( args: Array? = null, sortOrder: String? = null, block: (Cursor) -> R -) = query(uri, projection, selector, args, sortOrder)?.use(block) +) = safeQuery(uri, projection, selector, args, sortOrder).use(block) diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/RateLimitedContentResolver.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/RateLimitedContentResolver.kt new file mode 100644 index 000000000..548c139c4 --- /dev/null +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/RateLimitedContentResolver.kt @@ -0,0 +1,121 @@ +/* + * Copyright (c) 2024 Auxio Project + * RateLimitedContentResolver.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 . + */ + +package org.oxycblt.musikr.fs.device + +import android.content.ContentResolver +import android.database.Cursor +import android.net.Uri +import kotlin.math.min +import kotlinx.coroutines.delay +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.Semaphore +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.sync.withPermit + +/** + * A rate-limited wrapper around ContentResolver that uses a token bucket algorithm to limit the + * rate of queries. + * + * @param contentResolver The underlying ContentResolver to wrap + * @param maxTokens The maximum number of tokens in the bucket (burst capacity) + * @param refillRate The rate at which tokens are refilled per second + * @param maxConcurrency The maximum number of concurrent queries allowed + */ +internal class RateLimitedContentResolver( + private val contentResolver: ContentResolver, + private val maxTokens: Int = 1000, + private val refillRate: Double = 1000.0, // tokens per second + private val maxConcurrency: Int = 10 +) { + private val tokenBucket = TokenBucket(maxTokens, refillRate) + private val concurrencySemaphore = Semaphore(maxConcurrency) + + /** + * A rate-limited version of ContentResolver.query This is a suspend function that should be + * called from a coroutine + */ + suspend fun query( + uri: Uri, + projection: Array?, + selection: String?, + selectionArgs: Array?, + sortOrder: String? + ): Cursor? = + concurrencySemaphore.withPermit { + tokenBucket.acquire() + contentResolver.query(uri, projection, selection, selectionArgs, sortOrder) + } + + /** + * A shortcut for querying the database with automatic resource management. Rate-limited version + * of the useQuery extension function. This is a suspend function that should be called from a + * coroutine + */ + suspend inline fun useQuery( + uri: Uri, + projection: Array, + selector: String? = null, + args: Array? = null, + sortOrder: String? = null, + crossinline block: suspend (Cursor) -> R + ): R = + concurrencySemaphore.withPermit { + tokenBucket.acquire() + contentResolver.useQuery(uri, projection, selector, args, sortOrder) { cursor -> + block(cursor) + } + } + + /** Token bucket implementation for rate limiting */ + internal class TokenBucket( + private val maxTokens: Int, + private val refillRate: Double // tokens per second + ) { + private var tokens: Double = maxTokens.toDouble() + private var lastRefillTime: Long = System.currentTimeMillis() + private val mutex = Mutex() + private val tokenWaitTime = (1000.0 / refillRate).toLong() // milliseconds per token + + suspend fun acquire() { + mutex.withLock { + refill() + + // Wait until a token is available + while (tokens < 1.0) { + val waitTime = ((1.0 - tokens) * tokenWaitTime).toLong() + delay(waitTime) + refill() + } + + tokens -= 1.0 + } + } + + private fun refill() { + val now = System.currentTimeMillis() + val timePassed = now - lastRefillTime + val tokensToAdd = (timePassed / 1000.0) * refillRate + + if (tokensToAdd > 0) { + tokens = min(tokens + tokensToAdd, maxTokens.toDouble()) + lastRefillTime = now + } + } + } +} From 23615689bd3b69252747f408240dc52d557dbc04 Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Sun, 22 Jun 2025 16:45:39 -0600 Subject: [PATCH 3/5] music: make file tree cache configurable --- .../oxycblt/auxio/music/MusicRepository.kt | 9 ++- .../org/oxycblt/auxio/music/MusicSettings.kt | 8 ++- .../auxio/music/shim/NoOpFileTreeCache.kt | 61 +++++++++++++++++++ app/src/main/res/values/settings.xml | 1 + app/src/main/res/values/strings.xml | 2 + app/src/main/res/xml/preferences_root.xml | 5 ++ 6 files changed, 83 insertions(+), 3 deletions(-) create mode 100644 app/src/main/java/org/oxycblt/auxio/music/shim/NoOpFileTreeCache.kt diff --git a/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt b/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt index f83f202e9..8574205b2 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt @@ -29,6 +29,7 @@ import kotlinx.coroutines.withContext import kotlinx.coroutines.yield import org.oxycblt.auxio.image.covers.SettingCovers import org.oxycblt.auxio.music.MusicRepository.IndexingWorker +import org.oxycblt.auxio.music.shim.NoOpFileTreeCache import org.oxycblt.auxio.music.shim.WriteOnlyFileTreeCache import org.oxycblt.auxio.music.shim.WriteOnlyMutableCache import org.oxycblt.musikr.IndexingProgress @@ -396,8 +397,12 @@ constructor( val cache = if (withCache) cache else WriteOnlyMutableCache(cache) val covers = settingCovers.mutate(context, newRevision) val fileTreeCache = - if (withCache) FileTreeCache.from(context) - else WriteOnlyFileTreeCache(FileTreeCache.from(context)) + if (musicSettings.useFileTreeCache) { + if (withCache) FileTreeCache.from(context) + else WriteOnlyFileTreeCache(FileTreeCache.from(context)) + } else { + NoOpFileTreeCache() + } val query = Query(source = locations, exclude = excludedLocations) val storage = Storage(cache, covers, storedPlaylists, fileTreeCache) val interpretation = Interpretation(nameFactory, separators, withHidden) diff --git a/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt b/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt index 8317f67d8..08ee7a3a6 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt @@ -51,6 +51,8 @@ interface MusicSettings : Settings { var separators: String /** Whether to enable more advanced sorting by articles and numbers. */ val intelligentSorting: Boolean + /** Whether to use the file-system cache for improved loading times. */ + val useFileTreeCache: Boolean interface Listener { /** Called when the current music locations changed. */ @@ -133,6 +135,9 @@ class MusicSettingsImpl @Inject constructor(@ApplicationContext private val cont override val intelligentSorting: Boolean get() = sharedPreferences.getBoolean(getString(R.string.set_key_auto_sort_names), true) + override val useFileTreeCache: Boolean + get() = sharedPreferences.getBoolean(getString(R.string.set_key_fs_cache), true) + override fun onSettingChanged(key: String, listener: MusicSettings.Listener) { // TODO: Differentiate "hard reloads" (Need the cache) and "Soft reloads" // (just need to manipulate data) @@ -145,7 +150,8 @@ class MusicSettingsImpl @Inject constructor(@ApplicationContext private val cont getString(R.string.set_key_separators), getString(R.string.set_key_auto_sort_names), getString(R.string.set_key_with_hidden), - getString(R.string.set_key_exclude_non_music) -> { + getString(R.string.set_key_exclude_non_music), + getString(R.string.set_key_fs_cache) -> { L.d("Dispatching indexing setting change for $key") listener.onIndexingSettingChanged() } diff --git a/app/src/main/java/org/oxycblt/auxio/music/shim/NoOpFileTreeCache.kt b/app/src/main/java/org/oxycblt/auxio/music/shim/NoOpFileTreeCache.kt new file mode 100644 index 000000000..a28de5139 --- /dev/null +++ b/app/src/main/java/org/oxycblt/auxio/music/shim/NoOpFileTreeCache.kt @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2025 Auxio Project + * NoOpFileTreeCache.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 . + */ + +package org.oxycblt.auxio.music.shim + +import android.net.Uri +import org.oxycblt.musikr.fs.device.CachedDirectory +import org.oxycblt.musikr.fs.device.CachedFile +import org.oxycblt.musikr.fs.device.FileTree +import org.oxycblt.musikr.fs.device.FileTreeCache + +/** + * A no-op implementation of [FileTreeCache] that doesn't cache anything. This implementation always + * returns cache misses and discards all updates. + */ +class NoOpFileTreeCache : FileTreeCache { + override fun read(): FileTree = NoOpFileTree() +} + +/** + * A no-op implementation of [FileTree] that doesn't cache anything. All queries return null (cache + * miss) and all updates are discarded. + */ +class NoOpFileTree : FileTree { + override suspend fun queryDirectory(uri: Uri): CachedDirectory? { + // Always return null to simulate a cache miss + return null + } + + override suspend fun updateDirectory(uri: Uri, directory: CachedDirectory) { + // Do nothing - discard the update + } + + override suspend fun queryFile(uri: Uri): CachedFile? { + // Always return null to simulate a cache miss + return null + } + + override suspend fun updateFile(uri: Uri, file: CachedFile) { + // Do nothing - discard the update + } + + override suspend fun write() { + // Do nothing - no cache to write + } +} diff --git a/app/src/main/res/values/settings.xml b/app/src/main/res/values/settings.xml index 86e8d255a..fd5d1857b 100644 --- a/app/src/main/res/values/settings.xml +++ b/app/src/main/res/values/settings.xml @@ -15,6 +15,7 @@ auxio_observing auxio_music_dirs auxio_excluded_dirs + auxio_fs_cache auxio_cover_mode2 auxio_square_covers auxio_exclude_non_music diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 26d456242..9111f1465 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -315,6 +315,8 @@ Music folders Manage where music should be loaded from New folder + Use file-system cache + Improves loading times, but can prevent new music from being added Excluded folders Manage folders to exclude from music loading Refresh music diff --git a/app/src/main/res/xml/preferences_root.xml b/app/src/main/res/xml/preferences_root.xml index 12f8fb94b..a45aa9142 100644 --- a/app/src/main/res/xml/preferences_root.xml +++ b/app/src/main/res/xml/preferences_root.xml @@ -33,6 +33,11 @@ app:summary="@string/set_locations_desc" app:title="@string/set_locations" /> + + Date: Sun, 22 Jun 2025 19:31:02 -0600 Subject: [PATCH 4/5] music: update file tree cache setting position --- .../java/org/oxycblt/auxio/music/MusicSettings.kt | 2 +- app/src/main/res/xml/preferences_root.xml | 12 +++++++----- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt b/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt index 08ee7a3a6..01f6e15e9 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt @@ -136,7 +136,7 @@ class MusicSettingsImpl @Inject constructor(@ApplicationContext private val cont get() = sharedPreferences.getBoolean(getString(R.string.set_key_auto_sort_names), true) override val useFileTreeCache: Boolean - get() = sharedPreferences.getBoolean(getString(R.string.set_key_fs_cache), true) + get() = sharedPreferences.getBoolean(getString(R.string.set_key_fs_cache), false) override fun onSettingChanged(key: String, listener: MusicSettings.Listener) { // TODO: Differentiate "hard reloads" (Need the cache) and "Soft reloads" diff --git a/app/src/main/res/xml/preferences_root.xml b/app/src/main/res/xml/preferences_root.xml index a45aa9142..0b4009a44 100644 --- a/app/src/main/res/xml/preferences_root.xml +++ b/app/src/main/res/xml/preferences_root.xml @@ -33,16 +33,18 @@ app:summary="@string/set_locations_desc" app:title="@string/set_locations" /> - - + + + Date: Sun, 22 Jun 2025 19:56:09 -0600 Subject: [PATCH 5/5] build: bump to v4.0.6 --- CHANGELOG.md | 10 ++++++++++ app/build.gradle | 4 ++-- fastlane/metadata/android/en-US/changelogs/65.txt | 4 ++++ 3 files changed, 16 insertions(+), 2 deletions(-) create mode 100644 fastlane/metadata/android/en-US/changelogs/65.txt diff --git a/CHANGELOG.md b/CHANGELOG.md index 439efa33e..f05f3f5fd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,15 @@ # Changelog +## 4.0.6 + +#### What's Improved +- Added option to enable/disable the file tree cache (disabled by default) +to prevent the library from not being updated on Samsung devices + +#### What's Fixed +- Fixed loading failing/crashing the app on some devices +- Fixed file tree cache being stored in cache storage rather than app storage + ## 4.0.5 #### What's Improved diff --git a/app/build.gradle b/app/build.gradle index 713ae9f14..e12d5daf3 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -18,8 +18,8 @@ android { defaultConfig { applicationId namespace - versionName "4.0.5" - versionCode 64 + versionName "4.0.6" + versionCode 65 minSdk min_sdk targetSdk target_sdk diff --git a/fastlane/metadata/android/en-US/changelogs/65.txt b/fastlane/metadata/android/en-US/changelogs/65.txt new file mode 100644 index 000000000..92c904f12 --- /dev/null +++ b/fastlane/metadata/android/en-US/changelogs/65.txt @@ -0,0 +1,4 @@ +Auxio 4.0.0 completely overhauls the user experience, with a refreshed design based on the latest Material Design specs +and a brand new music loader with signifigant improvements to device and tag support. +This patch fixes music loading failing/crashing on some devices and makes a caching system that prevented the music library from updating on some devices. +For more information, see https://github.com/OxygenCobalt/Auxio/releases/tag/v4.0.6.