musikr: lower level pipeline setup

About 1.4x faster from user measurements
This commit is contained in:
Alexander Capehart
2025-08-14 12:32:49 -06:00
parent d0f760a589
commit 9b46ccfcd4
8 changed files with 429 additions and 291 deletions
@@ -19,15 +19,16 @@
package org.oxycblt.musikr package org.oxycblt.musikr
import android.content.Context import android.content.Context
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.flow.buffer
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.onStart
import org.oxycblt.musikr.pipeline.EvaluateStep import org.oxycblt.musikr.pipeline.EvaluateStep
import org.oxycblt.musikr.pipeline.ExploreStep import org.oxycblt.musikr.pipeline.ExploreStep
import org.oxycblt.musikr.pipeline.Explored
import org.oxycblt.musikr.pipeline.ExtractStep import org.oxycblt.musikr.pipeline.ExtractStep
import org.oxycblt.musikr.pipeline.Extracted
import org.oxycblt.musikr.util.merge
import org.oxycblt.musikr.util.tryAsyncWith
/** /**
* A highly opinionated, multi-threaded device music library. * A highly opinionated, multi-threaded device music library.
@@ -65,7 +66,6 @@ interface Musikr {
*/ */
fun new(context: Context, config: Config): Musikr = fun new(context: Context, config: Config): Musikr =
MusikrImpl( MusikrImpl(
context,
config, config,
ExploreStep.from(context, config), ExploreStep.from(context, config),
ExtractStep.from(context, config), ExtractStep.from(context, config),
@@ -106,28 +106,41 @@ sealed interface IndexingProgress {
} }
private class MusikrImpl( private class MusikrImpl(
private val context: Context,
private val config: Config, private val config: Config,
private val exploreStep: ExploreStep, private val exploreStep: ExploreStep,
private val extractStep: ExtractStep, private val extractStep: ExtractStep,
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 {
var exploredCount = 0 onProgress(IndexingProgress.Songs(0, 0))
var extractedCount = 0 val start = System.currentTimeMillis()
val explored = var explored = 0
exploreStep var loaded = 0
.explore() val exploredChannel = Channel<Explored>(Channel.UNLIMITED)
.buffer(Channel.UNLIMITED) val exploredTask = exploreStep.explore(this, exploredChannel)
.onStart { onProgress(IndexingProgress.Songs(0, 0)) } val trackedExploredChannel = Channel<Explored>(Channel.UNLIMITED)
.onEach { onProgress(IndexingProgress.Songs(extractedCount, ++exploredCount)) } val trackedExploredTask =
val extracted = tryAsyncWith(trackedExploredChannel, Dispatchers.Main) {
extractStep for (item in exploredChannel) {
.extract(explored) explored++
.buffer(Channel.UNLIMITED) onProgress(IndexingProgress.Songs(loaded, explored))
.onEach { onProgress(IndexingProgress.Songs(++extractedCount, exploredCount)) } trackedExploredChannel.send(item)
.onCompletion { onProgress(IndexingProgress.Indeterminate) } }
val library = evaluateStep.evaluate(extracted) }
val extractedChannel = Channel<Extracted>(Channel.UNLIMITED)
val extractedTask = extractStep.extract(this, trackedExploredChannel, extractedChannel)
val trackedExtractedChannel = Channel<Extracted>(Channel.UNLIMITED)
val trackedExtractedTask =
tryAsyncWith(trackedExtractedChannel, Dispatchers.Main) {
for (item in extractedChannel) {
loaded++
onProgress(IndexingProgress.Songs(loaded, explored))
trackedExtractedChannel.send(item)
}
onProgress(IndexingProgress.Indeterminate)
}
val library = evaluateStep.evaluate(trackedExtractedChannel)
merge(exploredTask, extractedTask, trackedExploredTask, trackedExtractedTask).await()
LibraryResultImpl(config, library) LibraryResultImpl(config, library)
} }
} }
@@ -20,10 +20,11 @@ package org.oxycblt.musikr.fs
import android.net.Uri import android.net.Uri
import kotlinx.coroutines.Deferred import kotlinx.coroutines.Deferred
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
interface FS { interface FS {
fun explore(): Flow<File> suspend fun explore(files: Channel<File>): Deferred<Result<Unit>>
fun track(): Flow<FSUpdate> fun track(): Flow<FSUpdate>
} }
@@ -22,12 +22,14 @@ import android.content.Context
import android.net.Uri import android.net.Uri
import android.provider.MediaStore as AOSPMediaStore import android.provider.MediaStore as AOSPMediaStore
import androidx.core.database.getStringOrNull import androidx.core.database.getStringOrNull
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.yield
import org.oxycblt.musikr.fs.AddedMs import org.oxycblt.musikr.fs.AddedMs
import org.oxycblt.musikr.fs.FS import org.oxycblt.musikr.fs.FS
import org.oxycblt.musikr.fs.FSUpdate import org.oxycblt.musikr.fs.FSUpdate
@@ -38,6 +40,7 @@ import org.oxycblt.musikr.fs.path.VolumeManager
import org.oxycblt.musikr.fs.saf.contentResolverSafe import org.oxycblt.musikr.fs.saf.contentResolverSafe
import org.oxycblt.musikr.fs.saf.useQuery import org.oxycblt.musikr.fs.saf.useQuery
import org.oxycblt.musikr.fs.track.LocationObserver import org.oxycblt.musikr.fs.track.LocationObserver
import org.oxycblt.musikr.util.tryAsyncWith
/** /**
* MediaStore implementation of [FS] that queries the Android MediaStore database for audio files * MediaStore implementation of [FS] that queries the Android MediaStore database for audio files
@@ -52,83 +55,88 @@ private constructor(
private val pathInterpreterFactory = MediaStorePathInterpreter.Factory.from(volumeManager) private val pathInterpreterFactory = MediaStorePathInterpreter.Factory.from(volumeManager)
@OptIn(ExperimentalCoroutinesApi::class) @OptIn(ExperimentalCoroutinesApi::class)
override fun explore(): Flow<File> = flow { override suspend fun explore(files: Channel<File>): Deferred<Result<Unit>> = coroutineScope {
val projection = BASE_PROJECTION + pathInterpreterFactory.projection tryAsyncWith(files, Dispatchers.IO) {
var selector = BASE_SELECTOR val projection = BASE_PROJECTION + pathInterpreterFactory.projection
val args = mutableListOf<String>() var selector = BASE_SELECTOR
val args = mutableListOf<String>()
// Filter out audio that is not music, if enabled // Filter out audio that is not music, if enabled
if (query.excludeNonMusic) { if (query.excludeNonMusic) {
selector += " AND ${AOSPMediaStore.Audio.AudioColumns.IS_MUSIC}=1" selector += " AND ${AOSPMediaStore.Audio.AudioColumns.IS_MUSIC}=1"
}
// Handle include/exclude directories
when (query.mode) {
FilterMode.INCLUDE -> {
val pathSelector =
pathInterpreterFactory.createSelector(query.filtered.map { it.path })
if (pathSelector != null) {
selector += " AND (${pathSelector.template})"
args.addAll(pathSelector.args)
}
}
FilterMode.EXCLUDE -> {
val pathSelector =
pathInterpreterFactory.createSelector(query.filtered.map { it.path })
if (pathSelector != null) {
selector += " AND NOT (${pathSelector.template})"
args.addAll(pathSelector.args)
}
}
}
// Collect all files and track unique directories
val allFiles = mutableListOf<File>()
context.contentResolverSafe.useQuery(
AOSPMediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
projection,
selector,
args.toTypedArray()) { cursor ->
val pathInterpreter = pathInterpreterFactory.wrap(cursor)
val idIndex =
cursor.getColumnIndexOrThrow(AOSPMediaStore.Audio.AudioColumns._ID)
val mimeTypeIndex =
cursor.getColumnIndexOrThrow(AOSPMediaStore.Audio.AudioColumns.MIME_TYPE)
val sizeIndex =
cursor.getColumnIndexOrThrow(AOSPMediaStore.Audio.AudioColumns.SIZE)
val dateAddedIndex =
cursor.getColumnIndexOrThrow(AOSPMediaStore.Audio.AudioColumns.DATE_ADDED)
val dateModifiedIndex =
cursor.getColumnIndexOrThrow(
AOSPMediaStore.Audio.AudioColumns.DATE_MODIFIED)
while (cursor.moveToNext()) {
val path = pathInterpreter.extract() ?: continue
val id = cursor.getLong(idIndex)
val uri =
Uri.withAppendedPath(
AOSPMediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id.toString())
val mimeType = cursor.getStringOrNull(mimeTypeIndex) ?: "audio/*"
val size = cursor.getLong(sizeIndex)
val dateAdded =
cursor.getLong(dateAddedIndex) * 1000 // Convert to milliseconds
val dateModified =
cursor.getLong(dateModifiedIndex) * 1000 // Convert to milliseconds
// Create file with empty deferred parent
val deviceFile =
File(
uri = uri,
path = path,
modifiedMs = dateModified,
mimeType = mimeType,
size = size,
addedMs = ForwardDateAdded(dateAdded),
parent = null)
allFiles.add(deviceFile)
it.send(deviceFile)
}
}
} }
// Handle include/exclude directories
when (query.mode) {
FilterMode.INCLUDE -> {
val pathSelector =
pathInterpreterFactory.createSelector(query.filtered.map { it.path })
if (pathSelector != null) {
selector += " AND (${pathSelector.template})"
args.addAll(pathSelector.args)
}
}
FilterMode.EXCLUDE -> {
val pathSelector =
pathInterpreterFactory.createSelector(query.filtered.map { it.path })
if (pathSelector != null) {
selector += " AND NOT (${pathSelector.template})"
args.addAll(pathSelector.args)
}
}
}
// Collect all files and track unique directories
val allFiles = mutableListOf<File>()
context.contentResolverSafe.useQuery(
AOSPMediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
projection,
selector,
args.toTypedArray()) { cursor ->
val pathInterpreter = pathInterpreterFactory.wrap(cursor)
val idIndex = cursor.getColumnIndexOrThrow(AOSPMediaStore.Audio.AudioColumns._ID)
val mimeTypeIndex =
cursor.getColumnIndexOrThrow(AOSPMediaStore.Audio.AudioColumns.MIME_TYPE)
val sizeIndex = cursor.getColumnIndexOrThrow(AOSPMediaStore.Audio.AudioColumns.SIZE)
val dateAddedIndex =
cursor.getColumnIndexOrThrow(AOSPMediaStore.Audio.AudioColumns.DATE_ADDED)
val dateModifiedIndex =
cursor.getColumnIndexOrThrow(AOSPMediaStore.Audio.AudioColumns.DATE_MODIFIED)
while (cursor.moveToNext()) {
val path = pathInterpreter.extract() ?: continue
val id = cursor.getLong(idIndex)
val uri =
Uri.withAppendedPath(
AOSPMediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id.toString())
val mimeType = cursor.getStringOrNull(mimeTypeIndex) ?: "audio/*"
val size = cursor.getLong(sizeIndex)
val dateAdded = cursor.getLong(dateAddedIndex) * 1000 // Convert to milliseconds
val dateModified =
cursor.getLong(dateModifiedIndex) * 1000 // Convert to milliseconds
// Create file with empty deferred parent
val deviceFile =
File(
uri = uri,
path = path,
modifiedMs = dateModified,
mimeType = mimeType,
size = size,
addedMs = ForwardDateAdded(dateAdded),
parent = null)
allFiles.add(deviceFile)
emit(deviceFile)
yield()
}
}
} }
override fun track(): Flow<FSUpdate> = callbackFlow { override fun track(): Flow<FSUpdate> = callbackFlow {
@@ -26,16 +26,15 @@ import android.provider.DocumentsContract
import android.provider.MediaStore as AOSPMediaStore import android.provider.MediaStore as AOSPMediaStore
import androidx.annotation.RequiresApi import androidx.annotation.RequiresApi
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.channels.Channel
import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.callbackFlow import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.emitAll
import kotlinx.coroutines.flow.flatMapMerge
import kotlinx.coroutines.flow.flattenMerge
import kotlinx.coroutines.flow.flow
import org.oxycblt.musikr.fs.AddedMs import org.oxycblt.musikr.fs.AddedMs
import org.oxycblt.musikr.fs.Directory import org.oxycblt.musikr.fs.Directory
import org.oxycblt.musikr.fs.FS import org.oxycblt.musikr.fs.FS
@@ -44,6 +43,9 @@ import org.oxycblt.musikr.fs.File
import org.oxycblt.musikr.fs.Location import org.oxycblt.musikr.fs.Location
import org.oxycblt.musikr.fs.Path import org.oxycblt.musikr.fs.Path
import org.oxycblt.musikr.fs.track.LocationObserver import org.oxycblt.musikr.fs.track.LocationObserver
import org.oxycblt.musikr.util.tryAsync
import org.oxycblt.musikr.util.tryAsyncWith
import org.oxycblt.musikr.util.tryAwaitAll
@OptIn(ExperimentalCoroutinesApi::class) @OptIn(ExperimentalCoroutinesApi::class)
class SAF class SAF
@@ -52,15 +54,21 @@ private constructor(
private val contentResolver: ContentResolver, private val contentResolver: ContentResolver,
private val query: Query private val query: Query
) : FS { ) : FS {
override fun explore(): Flow<File> = override suspend fun explore(files: Channel<File>): Deferred<Result<Unit>> = coroutineScope {
query.source.asFlow().flatMapMerge { location -> tryAsyncWith(files, Dispatchers.Main) {
exploreDirectoryImpl( query.source
location.uri, .map { location ->
DocumentsContract.getTreeDocumentId(location.uri), exploreDirectoryImpl(
location.path, location.uri,
null, DocumentsContract.getTreeDocumentId(location.uri),
query.exclude.mapTo(mutableSetOf()) { it.path }) location.path,
null,
query.exclude.mapTo(mutableSetOf()) { it.path },
files)
}
.tryAwaitAll()
} }
}
override fun track(): Flow<FSUpdate> = callbackFlow { override fun track(): Flow<FSUpdate> = callbackFlow {
val observers = mutableListOf<LocationObserver>() val observers = mutableListOf<LocationObserver>()
@@ -76,76 +84,79 @@ private constructor(
awaitClose { observers.forEach { observer -> observer.release() } } awaitClose { observers.forEach { observer -> observer.release() } }
} }
private fun exploreDirectoryImpl( private fun CoroutineScope.exploreDirectoryImpl(
rootUri: Uri, rootUri: Uri,
treeDocumentId: String, treeDocumentId: String,
relativePath: Path, relativePath: Path,
parent: Deferred<Directory>?, parent: Deferred<Directory>?,
exclude: Set<Path> exclude: Set<Path>,
): Flow<File> = flow { files: Channel<File>
// Make a kotlin future ): Deferred<Result<Unit>> =
val uri = DocumentsContract.buildChildDocumentsUriUsingTree(rootUri, treeDocumentId) tryAsync(Dispatchers.IO) {
val directoryDeferred = CompletableDeferred<Directory>() // Make a kotlin future
val recursive = mutableListOf<Flow<File>>() val uri = DocumentsContract.buildChildDocumentsUriUsingTree(rootUri, treeDocumentId)
val children = mutableListOf<File>() val directoryDeferred = CompletableDeferred<Directory>()
contentResolver.useQuery(uri, PROJECTION) { cursor -> val recursive = mutableListOf<Deferred<Result<Unit>>>()
val childUriIndex = val children = mutableListOf<File>()
cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DOCUMENT_ID) contentResolver.useQuery(uri, PROJECTION) { cursor ->
val displayNameIndex = val childUriIndex =
cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DISPLAY_NAME) cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DOCUMENT_ID)
val mimeTypeIndex = val displayNameIndex =
cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_MIME_TYPE) cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DISPLAY_NAME)
val sizeIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_SIZE) val mimeTypeIndex =
val lastModifiedIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_MIME_TYPE)
cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED) val sizeIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_SIZE)
val lastModifiedIndex =
cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED)
while (cursor.moveToNext()) { while (cursor.moveToNext()) {
val childId = cursor.getString(childUriIndex) val childId = cursor.getString(childUriIndex)
val displayName = cursor.getString(displayNameIndex) val displayName = cursor.getString(displayNameIndex)
// Skip hidden files/directories if ignoreHidden is true // Skip hidden files/directories if ignoreHidden is true
if (!query.withHidden && displayName.startsWith(".")) { if (!query.withHidden && displayName.startsWith(".")) {
continue continue
} }
val newPath = relativePath.file(displayName) val newPath = relativePath.file(displayName)
val mimeType = cursor.getString(mimeTypeIndex) val mimeType = cursor.getString(mimeTypeIndex)
val lastModified = cursor.getLong(lastModifiedIndex) val lastModified = cursor.getLong(lastModifiedIndex)
val childUri = DocumentsContract.buildDocumentUriUsingTree(rootUri, childId) val childUri = DocumentsContract.buildDocumentUriUsingTree(rootUri, childId)
// We can check for direct equality as if we block out an excluded directory we // We can check for direct equality as if we block out an excluded directory we
// will by proxy block out it's children. // will by proxy block out it's children.
if (newPath in exclude) { if (newPath in exclude) {
continue continue
} }
if (mimeType == DocumentsContract.Document.MIME_TYPE_DIR) { if (mimeType == DocumentsContract.Document.MIME_TYPE_DIR) {
recursive.add( recursive.add(
exploreDirectoryImpl(rootUri, childId, newPath, directoryDeferred, exclude)) exploreDirectoryImpl(
} else { rootUri, childId, newPath, directoryDeferred, exclude, files))
val size = cursor.getLong(sizeIndex) } else {
val file = val size = cursor.getLong(sizeIndex)
File( val file =
uri = childUri, File(
mimeType = mimeType, uri = childUri,
path = newPath, mimeType = mimeType,
size = size, path = newPath,
modifiedMs = lastModified, size = size,
parent = directoryDeferred, modifiedMs = lastModified,
addedMs = parent = directoryDeferred,
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { addedMs =
JoinAddedMs(context, childUri) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
} else { JoinAddedMs(context, childUri)
NullAddedMs } else {
}) NullAddedMs
children.add(file) })
emit(file) children.add(file)
files.send(file)
}
} }
directoryDeferred.complete(Directory(uri, relativePath, parent, children))
} }
directoryDeferred.complete(Directory(uri, relativePath, parent, children)) recursive.tryAwaitAll()
emitAll(recursive.asFlow().flattenMerge())
} }
}
data class Query( data class Query(
val source: List<Location.Opened>, val source: List<Location.Opened>,
@@ -18,8 +18,7 @@
package org.oxycblt.musikr.pipeline package org.oxycblt.musikr.pipeline
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.filterIsInstance
import org.oxycblt.musikr.Config import org.oxycblt.musikr.Config
import org.oxycblt.musikr.Interpretation import org.oxycblt.musikr.Interpretation
import org.oxycblt.musikr.MutableLibrary import org.oxycblt.musikr.MutableLibrary
@@ -30,7 +29,7 @@ import org.oxycblt.musikr.playlist.interpret.PlaylistInterpreter
import org.oxycblt.musikr.tag.interpret.TagInterpreter import org.oxycblt.musikr.tag.interpret.TagInterpreter
internal interface EvaluateStep { internal interface EvaluateStep {
suspend fun evaluate(extractedMusic: Flow<Extracted>): MutableLibrary suspend fun evaluate(extractedMusic: Channel<Extracted>): MutableLibrary
companion object { companion object {
fun new(config: Config, interpretation: Interpretation): EvaluateStep = fun new(config: Config, interpretation: Interpretation): EvaluateStep =
@@ -48,16 +47,16 @@ private class EvaluateStepImpl(
private val storedPlaylists: StoredPlaylists, private val storedPlaylists: StoredPlaylists,
private val libraryFactory: LibraryFactory private val libraryFactory: LibraryFactory
) : EvaluateStep { ) : EvaluateStep {
override suspend fun evaluate(extractedMusic: Flow<Extracted>): MutableLibrary = override suspend fun evaluate(extractedMusic: Channel<Extracted>): MutableLibrary {
extractedMusic val builder = MusicGraph.builder()
.filterIsInstance<Extracted.Valid>() for (extracted in extractedMusic) {
.tryFold(MusicGraph.builder()) { graphBuilder, extracted -> when (extracted) {
when (extracted) { is RawSong -> builder.add(tagInterpreter.interpret(extracted))
is RawSong -> graphBuilder.add(tagInterpreter.interpret(extracted)) is RawPlaylist -> builder.add(playlistInterpreter.interpret(extracted.file))
is RawPlaylist -> is InvalidSong -> {}
graphBuilder.add(playlistInterpreter.interpret(extracted.file))
}
graphBuilder
} }
.let { libraryFactory.create(it.build(), storedPlaylists, playlistInterpreter) } builder
}
return libraryFactory.create(builder.build(), storedPlaylists, playlistInterpreter)
}
} }
@@ -19,17 +19,10 @@
package org.oxycblt.musikr.pipeline package org.oxycblt.musikr.pipeline
import android.content.Context import android.content.Context
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.buffer
import kotlinx.coroutines.flow.emitAll
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.merge
import org.oxycblt.musikr.Config import org.oxycblt.musikr.Config
import org.oxycblt.musikr.Storage import org.oxycblt.musikr.Storage
import org.oxycblt.musikr.cache.CacheResult import org.oxycblt.musikr.cache.CacheResult
@@ -37,10 +30,13 @@ import org.oxycblt.musikr.cache.CachedSong
import org.oxycblt.musikr.covers.Cover import org.oxycblt.musikr.covers.Cover
import org.oxycblt.musikr.covers.CoverResult import org.oxycblt.musikr.covers.CoverResult
import org.oxycblt.musikr.fs.FS import org.oxycblt.musikr.fs.FS
import org.oxycblt.musikr.fs.File
import org.oxycblt.musikr.playlist.m3u.M3U import org.oxycblt.musikr.playlist.m3u.M3U
import org.oxycblt.musikr.util.merge
import org.oxycblt.musikr.util.tryAsyncWith
internal interface ExploreStep { internal interface ExploreStep {
fun explore(): Flow<Explored> suspend fun explore(scope: CoroutineScope, explored: Channel<Explored>): Deferred<Result<Unit>>
companion object { companion object {
fun from(context: Context, config: Config): ExploreStep = fun from(context: Context, config: Config): ExploreStep =
@@ -49,47 +45,77 @@ internal interface ExploreStep {
} }
private class ExploreStepImpl(private val fs: FS, private val storage: Storage) : ExploreStep { private class ExploreStepImpl(private val fs: FS, private val storage: Storage) : ExploreStep {
override fun explore(): Flow<Explored> { override suspend fun explore(
return merge( scope: CoroutineScope,
fs.explore() explored: Channel<Explored>
.filter { it.mimeType.startsWith("audio/") || it.mimeType == M3U.MIME_TYPE } ): Deferred<Result<Unit>> {
.distributedMap(n = 8, on = Dispatchers.IO, buffer = Channel.UNLIMITED) { file -> val files = Channel<File>(Channel.UNLIMITED)
when (val cacheResult = storage.cache.read(file)) { val filesTask = fs.explore(files)
is CacheResult.Hit -> NeedsCover(cacheResult.song)
is CacheResult.Stale -> Finalized(NewSong(cacheResult.file)) val classified = Channel<Classified>(Channel.UNLIMITED)
is CacheResult.Miss -> Finalized(NewSong(cacheResult.file)) val classifiedTask =
} scope.tryAsyncWith(classified, Dispatchers.IO) {
} for (file in files) {
.flowOn(Dispatchers.IO) if (file.mimeType.startsWith("audio/") || file.mimeType == M3U.MIME_TYPE) {
.buffer(Channel.UNLIMITED) val cacheResult = storage.cache.read(file)
.distributedMap(n = 8, on = Dispatchers.IO, buffer = Channel.UNLIMITED) { when (cacheResult) {
when (it) { is CacheResult.Hit -> it.send(NeedsCover(cacheResult.song))
is Finalized -> it is CacheResult.Stale -> it.send(Finalized(NewSong(cacheResult.file)))
is NeedsCover -> { is CacheResult.Miss -> it.send(Finalized(NewSong(cacheResult.file)))
when (val coverResult =
it.cachedSong.coverId?.let { id -> storage.covers.obtain(id) }) {
is CoverResult.Hit ->
Finalized(it.cachedSong.toRawSong(coverResult.cover))
null -> Finalized(it.cachedSong.toRawSong(null))
else -> Finalized(NewSong(it.cachedSong.file))
}
} }
} }
} }
.map { it.explored } }
.flowOn(Dispatchers.IO)
.buffer(Channel.UNLIMITED), val finalized = Channel<Explored>(Channel.UNLIMITED)
flow { emitAll(storage.storedPlaylists.read().asFlow()) } val exploredTask =
.map { RawPlaylist(it) } scope.tryAsyncWith(finalized, Dispatchers.IO) {
.flowOn(Dispatchers.IO) for (item in classified) {
.buffer(Channel.UNLIMITED)) val result =
when (item) {
is Finalized -> item
is NeedsCover -> {
when (val coverResult =
item.cachedSong.coverId?.let { id ->
storage.covers.obtain(id)
}) {
is CoverResult.Hit ->
Finalized(item.cachedSong.toRawSong(coverResult.cover))
null -> Finalized(item.cachedSong.toRawSong(null))
else -> Finalized(NewSong(item.cachedSong.file))
}
}
}
it.send(result.explored)
}
}
val playlists = Channel<Explored>(Channel.UNLIMITED)
val playlistsTask =
scope.tryAsyncWith(playlists, Dispatchers.IO) {
for (playlist in storage.storedPlaylists.read()) {
val rawPlaylist = RawPlaylist(playlist)
it.send(rawPlaylist)
}
}
val mergeTask =
scope.tryAsyncWith(explored, Dispatchers.Main) {
for (item in finalized) {
it.send(item)
}
for (playlist in playlists) {
it.send(playlist)
}
}
return scope.merge(filesTask, classifiedTask, exploredTask, playlistsTask, mergeTask)
} }
private sealed interface InternalExploreItem private sealed interface Classified
private data class NeedsCover(val cachedSong: CachedSong) : InternalExploreItem private data class NeedsCover(val cachedSong: CachedSong) : Classified
private data class Finalized(val explored: Explored) : InternalExploreItem private data class Finalized(val explored: Explored) : Classified
private fun CachedSong.toRawSong(cover: Cover?) = private fun CachedSong.toRawSong(cover: Cover?) =
RawSong(file, properties, tags, cover, addedMs) RawSong(file, properties, tags, cover, addedMs)
@@ -19,13 +19,10 @@
package org.oxycblt.musikr.pipeline package org.oxycblt.musikr.pipeline
import android.content.Context import android.content.Context
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.buffer
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onCompletion
import org.oxycblt.musikr.Config import org.oxycblt.musikr.Config
import org.oxycblt.musikr.cache.CachedSong import org.oxycblt.musikr.cache.CachedSong
import org.oxycblt.musikr.cache.MutableCache import org.oxycblt.musikr.cache.MutableCache
@@ -35,9 +32,16 @@ import org.oxycblt.musikr.covers.MutableCovers
import org.oxycblt.musikr.metadata.Metadata import org.oxycblt.musikr.metadata.Metadata
import org.oxycblt.musikr.metadata.MetadataExtractor import org.oxycblt.musikr.metadata.MetadataExtractor
import org.oxycblt.musikr.tag.parse.TagParser import org.oxycblt.musikr.tag.parse.TagParser
import org.oxycblt.musikr.util.merge
import org.oxycblt.musikr.util.tryAsyncWith
import org.oxycblt.musikr.util.tryParWith
internal interface ExtractStep { internal interface ExtractStep {
fun extract(nodes: Flow<Explored>): Flow<Extracted> suspend fun extract(
scope: CoroutineScope,
explored: Channel<Explored>,
extracted: Channel<Extracted>
): Deferred<Result<Unit>>
companion object { companion object {
fun from(context: Context, config: Config): ExtractStep = fun from(context: Context, config: Config): ExtractStep =
@@ -55,72 +59,81 @@ private class ExtractStepImpl(
private val cache: MutableCache, private val cache: MutableCache,
private val covers: MutableCovers<out Cover> private val covers: MutableCovers<out Cover>
) : ExtractStep { ) : ExtractStep {
override fun extract(nodes: Flow<Explored>): Flow<Extracted> { override suspend fun extract(
scope: CoroutineScope,
explored: Channel<Explored>,
extracted: Channel<Extracted>
): Deferred<Result<Unit>> {
val addingMs = System.currentTimeMillis() val addingMs = System.currentTimeMillis()
val exclude = mutableListOf<CachedSong>() val extract = Channel<ParsedExtractItem>(8)
return nodes val extractTask =
// Cover art is huge, so we have to kneecap the concurrency here to avoid excessive scope.tryParWith(8, explored, extract, Dispatchers.IO) { item ->
// GCs. We still reap the concurrency benefits here, just not as much as we could. when (item) {
.distributedMap(on = Dispatchers.IO, n = 8, buffer = Channel.RENDEZVOUS) { is RawSong -> Finalized(item)
when (it) { is RawPlaylist -> Finalized(item)
is RawSong -> Finalized(it)
is RawPlaylist -> Finalized(it)
is NewSong -> { is NewSong -> {
val metadata = metadataExtractor.extract(it.file) val metadata = metadataExtractor.extract(item.file)
if (metadata != null) NeedsParsing(it, metadata) else Finalized(InvalidSong) if (metadata != null) NeedsParsing(item, metadata)
else Finalized(InvalidSong)
} }
} }
} }
.flowOn(Dispatchers.IO) val parsed = Channel<ParsedCachingItem>(Channel.UNLIMITED)
.buffer(Channel.RENDEZVOUS) val parsedTask =
.distributedMap(on = Dispatchers.IO, n = 8, buffer = Channel.UNLIMITED) { scope.tryAsyncWith(parsed, Dispatchers.IO) {
when (it) { for (item in extract) {
is Finalized -> it val result =
is NeedsParsing -> { when (item) {
val tags = tagParser.parse(it.metadata) is Finalized -> item
val cover = is NeedsParsing -> {
when (val result = covers.create(it.newSong.file, it.metadata)) { val tags = tagParser.parse(item.metadata)
is CoverResult.Hit -> result.cover val cover =
else -> null when (val result =
covers.create(item.newSong.file, item.metadata)) {
is CoverResult.Hit -> result.cover
else -> null
}
NeedsCaching(
RawSong(
item.newSong.file,
item.metadata.properties,
tags,
cover,
// The thing about date added is that it's resolution can
// actually be expensive in some modes (ex. saf backend), so
// we resolve this by moving date added extraction as an
// extraction operation rather than doing the redundant work
// during exploration (well, kind of, MediaStore's date
// added query is basically free, it's only saf that has
// it's slow hacky workaround that we must accommodate
// here.)
item.newSong.file.addedMs.resolve() ?: addingMs))
} }
NeedsCaching( }
RawSong( parsed.send(result)
it.newSong.file, }
it.metadata.properties, }
tags, val finalizedTask =
cover, scope.tryAsyncWith(extracted, Dispatchers.IO) {
// The thing about date added is that it's resolution can actually val exclude = mutableListOf<CachedSong>()
// be expensive in some modes (ex. saf backend), so we resolve this for (item in parsed) {
// by val result =
// moving date added extraction as an extraction operation rather when (item) {
// than doing the redundant work during exploration (well, kind of, is Finalized -> item
// MediaStore's date added query is basically free, it's only saf is NeedsCaching -> {
// that has it's slow hacky workaround that we must accommodate cache.write(item.rawSong.toCachedSong())
// here.) Finalized(item.rawSong)
it.newSong.file.addedMs.resolve() ?: addingMs)) }
}
if (result.extracted is RawSong) {
exclude.add(result.extracted.toCachedSong())
} }
it.send(result.extracted)
} }
cache.cleanup(exclude)
} }
.flowOn(Dispatchers.IO)
.buffer(Channel.UNLIMITED) return scope.merge(extractTask, parsedTask, finalizedTask)
.distributedMap(on = Dispatchers.IO, n = 8, buffer = Channel.UNLIMITED) {
when (it) {
is Finalized -> it
is NeedsCaching -> {
cache.write(it.rawSong.toCachedSong())
Finalized(it.rawSong)
}
}
}
.map {
if (it.extracted is RawSong) {
exclude.add(it.extracted.toCachedSong())
}
it.extracted
}
.flowOn(Dispatchers.IO)
.buffer(Channel.UNLIMITED)
.onCompletion { cache.cleanup(exclude) }
} }
private sealed interface ParsedExtractItem private sealed interface ParsedExtractItem
@@ -20,10 +20,77 @@ package org.oxycblt.musikr.util
import java.security.MessageDigest import java.security.MessageDigest
import java.util.UUID import java.util.UUID
import kotlin.coroutines.CoroutineContext
import kotlin.reflect.KClass import kotlin.reflect.KClass
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.channels.Channel
import org.oxycblt.musikr.BuildConfig import org.oxycblt.musikr.BuildConfig
import org.oxycblt.musikr.tag.Date import org.oxycblt.musikr.tag.Date
fun CoroutineScope.tryAsync(
context: CoroutineContext,
block: suspend () -> Unit
): Deferred<Result<Unit>> = async {
try {
block()
Result.success(Unit)
} catch (e: Throwable) {
Result.failure(e)
}
}
fun <T> CoroutineScope.tryAsyncWith(
channel: Channel<T>,
context: CoroutineContext,
block: suspend (Channel<T>) -> Unit,
): Deferred<Result<Unit>> =
async(context) {
try {
block(channel)
channel.close()
Result.success(Unit)
} catch (e: Throwable) {
channel.close(e)
Result.failure(e)
}
}
fun <T, R> CoroutineScope.tryParWith(
n: Int,
channel: Channel<T>,
output: Channel<R>,
context: CoroutineContext = Dispatchers.Default,
block: suspend (T) -> R,
): Deferred<Result<Unit>> {
return tryAsync(context) {
val deferreds = ArrayList<Deferred<Result<Unit>>>()
for (i in 0 until n) {
val deferred =
tryAsync(context) {
for (item in channel) {
output.send(block(item))
}
}
deferreds.add(deferred)
}
deferreds.tryAwaitAll()
output.close()
Unit
}
}
suspend fun List<Deferred<Result<Unit>>>.tryAwaitAll() = awaitAll().forEach { it.getOrThrow() }
fun CoroutineScope.merge(vararg deferreds: Deferred<Result<Unit>>): Deferred<Result<Unit>> =
tryAsync(Dispatchers.Main) {
val results = awaitAll(*deferreds)
results.forEach { result -> result.getOrThrow() }
}
/** /**
* Sanitizes a value that is unlikely to be null. On debug builds, this aliases to [requireNotNull], * Sanitizes a value that is unlikely to be null. On debug builds, this aliases to [requireNotNull],
* otherwise, it aliases to the unchecked dereference operator (!!). This can be used as a minor * otherwise, it aliases to the unchecked dereference operator (!!). This can be used as a minor