musikr: introduce streaming file tree

Probably the best way I can go about this.
This commit is contained in:
Alexander Capehart
2025-05-13 19:45:04 -06:00
parent e3fe7c433d
commit 6905b51e66
5 changed files with 117 additions and 43 deletions
@@ -25,6 +25,9 @@ import android.os.ParcelFileDescriptor
import androidx.core.net.toUri import androidx.core.net.toUri
import java.io.InputStream import java.io.InputStream
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.filterIsInstance
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import org.oxycblt.musikr.covers.Cover import org.oxycblt.musikr.covers.Cover
import org.oxycblt.musikr.covers.CoverResult import org.oxycblt.musikr.covers.CoverResult
@@ -96,11 +99,12 @@ class MutableFSCovers(private val context: Context) : MutableCovers<FDCover> {
override suspend fun create(file: DeviceFile, metadata: Metadata): CoverResult<FDCover> { override suspend fun create(file: DeviceFile, metadata: Metadata): CoverResult<FDCover> {
// Since DeviceFiles is a streaming API, we have to wait for the current recursive // Since DeviceFiles is a streaming API, we have to wait for the current recursive
// query to finally finish to be able to have a complete list of siblings to search for. // query to finally finish to be able to have a complete list of siblings to search for.
val parent = file.parent.await() val parent = file.parent
val bestCover = val bestCover =
parent.children parent.children.flow()
.filterIsInstance<DeviceFile>() .filterIsInstance<DeviceFile>()
.map { it to coverArtScore(it) } .map { it to coverArtScore(it) }
.toList()
.maxBy { it.second } .maxBy { it.second }
if (bestCover.second > 0) { if (bestCover.second > 0) {
return CoverResult.Hit(FolderCoverImpl(context, bestCover.first.uri)) return CoverResult.Hit(FolderCoverImpl(context, bestCover.first.uri))
@@ -128,7 +132,7 @@ class MutableFSCovers(private val context: Context) : MutableCovers<FDCover> {
// See if the name contains any of the preferred cover names. This helps weed out // See if the name contains any of the preferred cover names. This helps weed out
// images that are not actually cover art and are just there., // images that are not actually cover art and are just there.,
var score = var score =
(preferredCoverNames + requireNotNull(file.parent.await().path.name)) (preferredCoverNames + requireNotNull(file.parent.path.name))
.withIndex() .withIndex()
.filter { name.contains(it.value, ignoreCase = true) } .filter { name.contains(it.value, ignoreCase = true) }
.sumOf { it.index + 1 } .sumOf { it.index + 1 }
@@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package org.oxycblt.musikr.fs.device package org.oxycblt.musikr.fs.device
import android.content.ContentResolver import android.content.ContentResolver
@@ -23,19 +23,23 @@ import android.content.Context
import android.net.Uri import android.net.Uri
import android.provider.DocumentsContract import android.provider.DocumentsContract
import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Deferred import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.asFlow import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.emitAll import kotlinx.coroutines.flow.emitAll
import kotlinx.coroutines.flow.flatMapMerge import kotlinx.coroutines.flow.flatMapMerge
import kotlinx.coroutines.flow.flattenMerge import kotlinx.coroutines.flow.flattenMerge
import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.map
import org.oxycblt.musikr.fs.MusicLocation import org.oxycblt.musikr.fs.MusicLocation
import org.oxycblt.musikr.fs.Path import org.oxycblt.musikr.fs.Path
internal interface DeviceFS { internal interface DeviceFS {
fun explore(locations: Flow<MusicLocation>): Flow<DeviceFile> fun explore(locations: Flow<MusicLocation>): Flow<DeviceDirectory>
companion object { companion object {
fun from(context: Context, withHidden: Boolean): DeviceFS = fun from(context: Context, withHidden: Boolean): DeviceFS =
@@ -48,27 +52,39 @@ private class DeviceFSImpl(
private val contentResolver: ContentResolver, private val contentResolver: ContentResolver,
private val withHidden: Boolean private val withHidden: Boolean
) : DeviceFS { ) : DeviceFS {
override fun explore(locations: Flow<MusicLocation>): Flow<DeviceFile> = override fun explore(locations: Flow<MusicLocation>): Flow<DeviceDirectory> =
locations.flatMapMerge { location -> locations.map { location ->
exploreDirectoryImpl( coroutineScope {
location.uri, DeviceDirectoryImpl(
DocumentsContract.getTreeDocumentId(location.uri), location.uri,
location.path, DocumentsContract.getTreeDocumentId(location.uri),
null) location.path,
null,
coroutineScope = CoroutineScope(Dispatchers.IO),
contentResolver = contentResolver,
withHidden = withHidden
)
}
} }
}
private fun exploreDirectoryImpl( private class DeviceDirectoryImpl(
rootUri: Uri, rootUri: Uri,
treeDocumentId: String, treeDocumentId: String,
relativePath: Path, override val path: Path,
parent: Deferred<DeviceDirectory>? override val parent: DeviceDirectoryImpl?,
): Flow<DeviceFile> = flow { coroutineScope: CoroutineScope,
// Make a kotlin future contentResolver: ContentResolver,
val uri = DocumentsContract.buildChildDocumentsUriUsingTree(rootUri, treeDocumentId) withHidden: Boolean
val directoryDeferred = CompletableDeferred<DeviceDirectory>() ) : DeviceDirectory {
val recursive = mutableListOf<Flow<DeviceFile>>() override val uri: Uri = DocumentsContract.buildDocumentUriUsingTree(rootUri, treeDocumentId)
val children = mutableListOf<DeviceFSEntry>() override val children = FiniteHotFlow<DeviceFSEntry>(coroutineScope) { emit ->
contentResolver.useQuery(uri, PROJECTION) { cursor -> contentResolver.useQuery(
DocumentsContract.buildChildDocumentsUriUsingTree(
rootUri,
treeDocumentId
), PROJECTION
) { cursor ->
val childUriIndex = val childUriIndex =
cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DOCUMENT_ID) cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DOCUMENT_ID)
val displayNameIndex = val displayNameIndex =
@@ -88,13 +104,22 @@ private class DeviceFSImpl(
continue continue
} }
val newPath = relativePath.file(displayName) val newPath = path.file(displayName)
val mimeType = cursor.getString(mimeTypeIndex) val mimeType = cursor.getString(mimeTypeIndex)
val lastModified = cursor.getLong(lastModifiedIndex) val lastModified = cursor.getLong(lastModifiedIndex)
if (mimeType == DocumentsContract.Document.MIME_TYPE_DIR) { if (mimeType == DocumentsContract.Document.MIME_TYPE_DIR) {
recursive.add( emit(
exploreDirectoryImpl(rootUri, childId, newPath, directoryDeferred)) DeviceDirectoryImpl(
rootUri,
childId,
path = newPath,
parent = this,
coroutineScope,
contentResolver,
withHidden
)
)
} else { } else {
val size = cursor.getLong(sizeIndex) val size = cursor.getLong(sizeIndex)
val childUri = DocumentsContract.buildDocumentUriUsingTree(rootUri, childId) val childUri = DocumentsContract.buildDocumentUriUsingTree(rootUri, childId)
@@ -105,23 +130,24 @@ private class DeviceFSImpl(
path = newPath, path = newPath,
size = size, size = size,
modifiedMs = lastModified, modifiedMs = lastModified,
parent = directoryDeferred) parent = this
children.add(file) )
emit(file) emit(file)
} }
} }
directoryDeferred.complete(DeviceDirectory(uri, relativePath, parent, children))
emitAll(recursive.asFlow().flattenMerge())
} }
} }
private companion object { private companion object {
val PROJECTION = private val PROJECTION =
arrayOf( arrayOf(
DocumentsContract.Document.COLUMN_DOCUMENT_ID, DocumentsContract.Document.COLUMN_DOCUMENT_ID,
DocumentsContract.Document.COLUMN_DISPLAY_NAME, DocumentsContract.Document.COLUMN_DISPLAY_NAME,
DocumentsContract.Document.COLUMN_MIME_TYPE, DocumentsContract.Document.COLUMN_MIME_TYPE,
DocumentsContract.Document.COLUMN_SIZE, DocumentsContract.Document.COLUMN_SIZE,
DocumentsContract.Document.COLUMN_LAST_MODIFIED) DocumentsContract.Document.COLUMN_LAST_MODIFIED
)
} }
} }
@@ -20,6 +20,10 @@ package org.oxycblt.musikr.fs.device
import android.net.Uri import android.net.Uri
import kotlinx.coroutines.Deferred import kotlinx.coroutines.Deferred
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flatMapMerge
import kotlinx.coroutines.flow.flowOf
import org.oxycblt.musikr.fs.Path import org.oxycblt.musikr.fs.Path
sealed interface DeviceFSEntry { sealed interface DeviceFSEntry {
@@ -27,12 +31,10 @@ sealed interface DeviceFSEntry {
val path: Path val path: Path
} }
data class DeviceDirectory( interface DeviceDirectory : DeviceFSEntry {
override val uri: Uri, val parent: DeviceDirectory?
override val path: Path, val children: FiniteHotFlow<DeviceFSEntry>
val parent: Deferred<DeviceDirectory>?, }
var children: List<DeviceFSEntry>
) : DeviceFSEntry
data class DeviceFile( data class DeviceFile(
override val uri: Uri, override val uri: Uri,
@@ -40,5 +42,13 @@ data class DeviceFile(
val modifiedMs: Long, val modifiedMs: Long,
val mimeType: String, val mimeType: String,
val size: Long, val size: Long,
val parent: Deferred<DeviceDirectory> val parent: DeviceDirectory
) : DeviceFSEntry ) : DeviceFSEntry
@OptIn(ExperimentalCoroutinesApi::class)
fun DeviceDirectory.flatten(): Flow<DeviceFile> = children.flow().flatMapMerge {
when (it) {
is DeviceDirectory -> it.flatten()
is DeviceFile -> flowOf(it)
}
}
@@ -0,0 +1,31 @@
package org.oxycblt.musikr.fs.device
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.FlowCollector
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.shareIn
import kotlinx.coroutines.flow.takeWhile
class FiniteHotFlow<T>(scope: CoroutineScope, emitter: suspend (emit: suspend (T) -> Unit) -> Unit) {
private sealed interface HotObject<T> {
data class More<T>(val value: T) : HotObject<T>
data object Done : HotObject<Nothing>
}
private val sharedFlow = flow {
emitter {
emit(HotObject.More(it))
}
emit(HotObject.Done)
}.shareIn(scope, SharingStarted.Lazily, replay = Int.MAX_VALUE)
@Suppress("UNCHECKED_CAST")
fun flow() = flow {
sharedFlow.takeWhile { it is HotObject.More<*> }.collect {
emit((it as HotObject.More<*>).value as T)
}
}
}
@@ -20,12 +20,14 @@ package org.oxycblt.musikr.pipeline
import android.content.Context import android.content.Context
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.asFlow import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.buffer import kotlinx.coroutines.flow.buffer
import kotlinx.coroutines.flow.emitAll import kotlinx.coroutines.flow.emitAll
import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.flatMapMerge
import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.map
@@ -40,6 +42,7 @@ import org.oxycblt.musikr.covers.CoverResult
import org.oxycblt.musikr.covers.Covers import org.oxycblt.musikr.covers.Covers
import org.oxycblt.musikr.fs.MusicLocation import org.oxycblt.musikr.fs.MusicLocation
import org.oxycblt.musikr.fs.device.DeviceFS import org.oxycblt.musikr.fs.device.DeviceFS
import org.oxycblt.musikr.fs.device.flatten
import org.oxycblt.musikr.playlist.db.StoredPlaylists import org.oxycblt.musikr.playlist.db.StoredPlaylists
import org.oxycblt.musikr.playlist.m3u.M3U import org.oxycblt.musikr.playlist.m3u.M3U
@@ -62,13 +65,13 @@ private class ExploreStepImpl(
private val covers: Covers<out Cover>, private val covers: Covers<out Cover>,
private val storedPlaylists: StoredPlaylists private val storedPlaylists: StoredPlaylists
) : ExploreStep { ) : ExploreStep {
@OptIn(ExperimentalCoroutinesApi::class)
override fun explore(locations: List<MusicLocation>): Flow<Explored> { override fun explore(locations: List<MusicLocation>): Flow<Explored> {
val addingMs = System.currentTimeMillis() val addingMs = System.currentTimeMillis()
return merge( return merge(
deviceFS deviceFS
.explore( .explore(locations.asFlow())
locations.asFlow(), .flatMapMerge { it.flatten() }
)
.filter { it.mimeType.startsWith("audio/") || it.mimeType == M3U.MIME_TYPE } .filter { it.mimeType.startsWith("audio/") || it.mimeType == M3U.MIME_TYPE }
.distributedMap(n = 8, on = Dispatchers.IO, buffer = Channel.UNLIMITED) { file -> .distributedMap(n = 8, on = Dispatchers.IO, buffer = Channel.UNLIMITED) { file ->
when (val cacheResult = cache.read(file)) { when (val cacheResult = cache.read(file)) {