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
import android.content.Context
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
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.ExploreStep
import org.oxycblt.musikr.pipeline.Explored
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.
@@ -65,7 +66,6 @@ interface Musikr {
*/
fun new(context: Context, config: Config): Musikr =
MusikrImpl(
context,
config,
ExploreStep.from(context, config),
ExtractStep.from(context, config),
@@ -106,28 +106,41 @@ sealed interface IndexingProgress {
}
private class MusikrImpl(
private val context: Context,
private val config: Config,
private val exploreStep: ExploreStep,
private val extractStep: ExtractStep,
private val evaluateStep: EvaluateStep
) : Musikr {
override suspend fun run(onProgress: suspend (IndexingProgress) -> Unit) = coroutineScope {
var exploredCount = 0
var extractedCount = 0
val explored =
exploreStep
.explore()
.buffer(Channel.UNLIMITED)
.onStart { onProgress(IndexingProgress.Songs(0, 0)) }
.onEach { onProgress(IndexingProgress.Songs(extractedCount, ++exploredCount)) }
val extracted =
extractStep
.extract(explored)
.buffer(Channel.UNLIMITED)
.onEach { onProgress(IndexingProgress.Songs(++extractedCount, exploredCount)) }
.onCompletion { onProgress(IndexingProgress.Indeterminate) }
val library = evaluateStep.evaluate(extracted)
onProgress(IndexingProgress.Songs(0, 0))
val start = System.currentTimeMillis()
var explored = 0
var loaded = 0
val exploredChannel = Channel<Explored>(Channel.UNLIMITED)
val exploredTask = exploreStep.explore(this, exploredChannel)
val trackedExploredChannel = Channel<Explored>(Channel.UNLIMITED)
val trackedExploredTask =
tryAsyncWith(trackedExploredChannel, Dispatchers.Main) {
for (item in exploredChannel) {
explored++
onProgress(IndexingProgress.Songs(loaded, explored))
trackedExploredChannel.send(item)
}
}
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)
}
}
@@ -20,10 +20,11 @@ package org.oxycblt.musikr.fs
import android.net.Uri
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
interface FS {
fun explore(): Flow<File>
suspend fun explore(files: Channel<File>): Deferred<Result<Unit>>
fun track(): Flow<FSUpdate>
}
@@ -22,12 +22,14 @@ import android.content.Context
import android.net.Uri
import android.provider.MediaStore as AOSPMediaStore
import androidx.core.database.getStringOrNull
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.Flow
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.FS
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.useQuery
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
@@ -52,83 +55,88 @@ private constructor(
private val pathInterpreterFactory = MediaStorePathInterpreter.Factory.from(volumeManager)
@OptIn(ExperimentalCoroutinesApi::class)
override fun explore(): Flow<File> = flow {
val projection = BASE_PROJECTION + pathInterpreterFactory.projection
var selector = BASE_SELECTOR
val args = mutableListOf<String>()
override suspend fun explore(files: Channel<File>): Deferred<Result<Unit>> = coroutineScope {
tryAsyncWith(files, Dispatchers.IO) {
val projection = BASE_PROJECTION + pathInterpreterFactory.projection
var selector = BASE_SELECTOR
val args = mutableListOf<String>()
// Filter out audio that is not music, if enabled
if (query.excludeNonMusic) {
selector += " AND ${AOSPMediaStore.Audio.AudioColumns.IS_MUSIC}=1"
// Filter out audio that is not music, if enabled
if (query.excludeNonMusic) {
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 {
@@ -26,16 +26,15 @@ import android.provider.DocumentsContract
import android.provider.MediaStore as AOSPMediaStore
import androidx.annotation.RequiresApi
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.asFlow
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.Directory
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.Path
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)
class SAF
@@ -52,15 +54,21 @@ private constructor(
private val contentResolver: ContentResolver,
private val query: Query
) : FS {
override fun explore(): Flow<File> =
query.source.asFlow().flatMapMerge { location ->
exploreDirectoryImpl(
location.uri,
DocumentsContract.getTreeDocumentId(location.uri),
location.path,
null,
query.exclude.mapTo(mutableSetOf()) { it.path })
override suspend fun explore(files: Channel<File>): Deferred<Result<Unit>> = coroutineScope {
tryAsyncWith(files, Dispatchers.Main) {
query.source
.map { location ->
exploreDirectoryImpl(
location.uri,
DocumentsContract.getTreeDocumentId(location.uri),
location.path,
null,
query.exclude.mapTo(mutableSetOf()) { it.path },
files)
}
.tryAwaitAll()
}
}
override fun track(): Flow<FSUpdate> = callbackFlow {
val observers = mutableListOf<LocationObserver>()
@@ -76,76 +84,79 @@ private constructor(
awaitClose { observers.forEach { observer -> observer.release() } }
}
private fun exploreDirectoryImpl(
private fun CoroutineScope.exploreDirectoryImpl(
rootUri: Uri,
treeDocumentId: String,
relativePath: Path,
parent: Deferred<Directory>?,
exclude: Set<Path>
): Flow<File> = flow {
// Make a kotlin future
val uri = DocumentsContract.buildChildDocumentsUriUsingTree(rootUri, treeDocumentId)
val directoryDeferred = CompletableDeferred<Directory>()
val recursive = mutableListOf<Flow<File>>()
val children = mutableListOf<File>()
contentResolver.useQuery(uri, PROJECTION) { cursor ->
val childUriIndex =
cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DOCUMENT_ID)
val displayNameIndex =
cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DISPLAY_NAME)
val mimeTypeIndex =
cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_MIME_TYPE)
val sizeIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_SIZE)
val lastModifiedIndex =
cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED)
exclude: Set<Path>,
files: Channel<File>
): Deferred<Result<Unit>> =
tryAsync(Dispatchers.IO) {
// Make a kotlin future
val uri = DocumentsContract.buildChildDocumentsUriUsingTree(rootUri, treeDocumentId)
val directoryDeferred = CompletableDeferred<Directory>()
val recursive = mutableListOf<Deferred<Result<Unit>>>()
val children = mutableListOf<File>()
contentResolver.useQuery(uri, PROJECTION) { cursor ->
val childUriIndex =
cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DOCUMENT_ID)
val displayNameIndex =
cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DISPLAY_NAME)
val mimeTypeIndex =
cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_MIME_TYPE)
val sizeIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_SIZE)
val lastModifiedIndex =
cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED)
while (cursor.moveToNext()) {
val childId = cursor.getString(childUriIndex)
val displayName = cursor.getString(displayNameIndex)
while (cursor.moveToNext()) {
val childId = cursor.getString(childUriIndex)
val displayName = cursor.getString(displayNameIndex)
// Skip hidden files/directories if ignoreHidden is true
if (!query.withHidden && displayName.startsWith(".")) {
continue
}
// Skip hidden files/directories if ignoreHidden is true
if (!query.withHidden && displayName.startsWith(".")) {
continue
}
val newPath = relativePath.file(displayName)
val mimeType = cursor.getString(mimeTypeIndex)
val lastModified = cursor.getLong(lastModifiedIndex)
val childUri = DocumentsContract.buildDocumentUriUsingTree(rootUri, childId)
val newPath = relativePath.file(displayName)
val mimeType = cursor.getString(mimeTypeIndex)
val lastModified = cursor.getLong(lastModifiedIndex)
val childUri = DocumentsContract.buildDocumentUriUsingTree(rootUri, childId)
// We can check for direct equality as if we block out an excluded directory we
// will by proxy block out it's children.
if (newPath in exclude) {
continue
}
// We can check for direct equality as if we block out an excluded directory we
// will by proxy block out it's children.
if (newPath in exclude) {
continue
}
if (mimeType == DocumentsContract.Document.MIME_TYPE_DIR) {
recursive.add(
exploreDirectoryImpl(rootUri, childId, newPath, directoryDeferred, exclude))
} else {
val size = cursor.getLong(sizeIndex)
val file =
File(
uri = childUri,
mimeType = mimeType,
path = newPath,
size = size,
modifiedMs = lastModified,
parent = directoryDeferred,
addedMs =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
JoinAddedMs(context, childUri)
} else {
NullAddedMs
})
children.add(file)
emit(file)
if (mimeType == DocumentsContract.Document.MIME_TYPE_DIR) {
recursive.add(
exploreDirectoryImpl(
rootUri, childId, newPath, directoryDeferred, exclude, files))
} else {
val size = cursor.getLong(sizeIndex)
val file =
File(
uri = childUri,
mimeType = mimeType,
path = newPath,
size = size,
modifiedMs = lastModified,
parent = directoryDeferred,
addedMs =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
JoinAddedMs(context, childUri)
} else {
NullAddedMs
})
children.add(file)
files.send(file)
}
}
directoryDeferred.complete(Directory(uri, relativePath, parent, children))
}
directoryDeferred.complete(Directory(uri, relativePath, parent, children))
emitAll(recursive.asFlow().flattenMerge())
recursive.tryAwaitAll()
}
}
data class Query(
val source: List<Location.Opened>,
@@ -18,8 +18,7 @@
package org.oxycblt.musikr.pipeline
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.filterIsInstance
import kotlinx.coroutines.channels.Channel
import org.oxycblt.musikr.Config
import org.oxycblt.musikr.Interpretation
import org.oxycblt.musikr.MutableLibrary
@@ -30,7 +29,7 @@ import org.oxycblt.musikr.playlist.interpret.PlaylistInterpreter
import org.oxycblt.musikr.tag.interpret.TagInterpreter
internal interface EvaluateStep {
suspend fun evaluate(extractedMusic: Flow<Extracted>): MutableLibrary
suspend fun evaluate(extractedMusic: Channel<Extracted>): MutableLibrary
companion object {
fun new(config: Config, interpretation: Interpretation): EvaluateStep =
@@ -48,16 +47,16 @@ private class EvaluateStepImpl(
private val storedPlaylists: StoredPlaylists,
private val libraryFactory: LibraryFactory
) : EvaluateStep {
override suspend fun evaluate(extractedMusic: Flow<Extracted>): MutableLibrary =
extractedMusic
.filterIsInstance<Extracted.Valid>()
.tryFold(MusicGraph.builder()) { graphBuilder, extracted ->
when (extracted) {
is RawSong -> graphBuilder.add(tagInterpreter.interpret(extracted))
is RawPlaylist ->
graphBuilder.add(playlistInterpreter.interpret(extracted.file))
}
graphBuilder
override suspend fun evaluate(extractedMusic: Channel<Extracted>): MutableLibrary {
val builder = MusicGraph.builder()
for (extracted in extractedMusic) {
when (extracted) {
is RawSong -> builder.add(tagInterpreter.interpret(extracted))
is RawPlaylist -> builder.add(playlistInterpreter.interpret(extracted.file))
is InvalidSong -> {}
}
.let { libraryFactory.create(it.build(), storedPlaylists, playlistInterpreter) }
builder
}
return libraryFactory.create(builder.build(), storedPlaylists, playlistInterpreter)
}
}
@@ -19,17 +19,10 @@
package org.oxycblt.musikr.pipeline
import android.content.Context
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
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.Storage
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.CoverResult
import org.oxycblt.musikr.fs.FS
import org.oxycblt.musikr.fs.File
import org.oxycblt.musikr.playlist.m3u.M3U
import org.oxycblt.musikr.util.merge
import org.oxycblt.musikr.util.tryAsyncWith
internal interface ExploreStep {
fun explore(): Flow<Explored>
suspend fun explore(scope: CoroutineScope, explored: Channel<Explored>): Deferred<Result<Unit>>
companion object {
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 {
override fun explore(): Flow<Explored> {
return merge(
fs.explore()
.filter { it.mimeType.startsWith("audio/") || it.mimeType == M3U.MIME_TYPE }
.distributedMap(n = 8, on = Dispatchers.IO, buffer = Channel.UNLIMITED) { file ->
when (val cacheResult = storage.cache.read(file)) {
is CacheResult.Hit -> NeedsCover(cacheResult.song)
is CacheResult.Stale -> Finalized(NewSong(cacheResult.file))
is CacheResult.Miss -> Finalized(NewSong(cacheResult.file))
}
}
.flowOn(Dispatchers.IO)
.buffer(Channel.UNLIMITED)
.distributedMap(n = 8, on = Dispatchers.IO, buffer = Channel.UNLIMITED) {
when (it) {
is Finalized -> it
is NeedsCover -> {
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))
}
override suspend fun explore(
scope: CoroutineScope,
explored: Channel<Explored>
): Deferred<Result<Unit>> {
val files = Channel<File>(Channel.UNLIMITED)
val filesTask = fs.explore(files)
val classified = Channel<Classified>(Channel.UNLIMITED)
val classifiedTask =
scope.tryAsyncWith(classified, Dispatchers.IO) {
for (file in files) {
if (file.mimeType.startsWith("audio/") || file.mimeType == M3U.MIME_TYPE) {
val cacheResult = storage.cache.read(file)
when (cacheResult) {
is CacheResult.Hit -> it.send(NeedsCover(cacheResult.song))
is CacheResult.Stale -> it.send(Finalized(NewSong(cacheResult.file)))
is CacheResult.Miss -> it.send(Finalized(NewSong(cacheResult.file)))
}
}
}
.map { it.explored }
.flowOn(Dispatchers.IO)
.buffer(Channel.UNLIMITED),
flow { emitAll(storage.storedPlaylists.read().asFlow()) }
.map { RawPlaylist(it) }
.flowOn(Dispatchers.IO)
.buffer(Channel.UNLIMITED))
}
val finalized = Channel<Explored>(Channel.UNLIMITED)
val exploredTask =
scope.tryAsyncWith(finalized, Dispatchers.IO) {
for (item in classified) {
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?) =
RawSong(file, properties, tags, cover, addedMs)
@@ -19,13 +19,10 @@
package org.oxycblt.musikr.pipeline
import android.content.Context
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
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.cache.CachedSong
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.MetadataExtractor
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 {
fun extract(nodes: Flow<Explored>): Flow<Extracted>
suspend fun extract(
scope: CoroutineScope,
explored: Channel<Explored>,
extracted: Channel<Extracted>
): Deferred<Result<Unit>>
companion object {
fun from(context: Context, config: Config): ExtractStep =
@@ -55,72 +59,81 @@ private class ExtractStepImpl(
private val cache: MutableCache,
private val covers: MutableCovers<out Cover>
) : 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 exclude = mutableListOf<CachedSong>()
return nodes
// Cover art is huge, so we have to kneecap the concurrency here to avoid excessive
// GCs. We still reap the concurrency benefits here, just not as much as we could.
.distributedMap(on = Dispatchers.IO, n = 8, buffer = Channel.RENDEZVOUS) {
when (it) {
is RawSong -> Finalized(it)
is RawPlaylist -> Finalized(it)
val extract = Channel<ParsedExtractItem>(8)
val extractTask =
scope.tryParWith(8, explored, extract, Dispatchers.IO) { item ->
when (item) {
is RawSong -> Finalized(item)
is RawPlaylist -> Finalized(item)
is NewSong -> {
val metadata = metadataExtractor.extract(it.file)
if (metadata != null) NeedsParsing(it, metadata) else Finalized(InvalidSong)
val metadata = metadataExtractor.extract(item.file)
if (metadata != null) NeedsParsing(item, metadata)
else Finalized(InvalidSong)
}
}
}
.flowOn(Dispatchers.IO)
.buffer(Channel.RENDEZVOUS)
.distributedMap(on = Dispatchers.IO, n = 8, buffer = Channel.UNLIMITED) {
when (it) {
is Finalized -> it
is NeedsParsing -> {
val tags = tagParser.parse(it.metadata)
val cover =
when (val result = covers.create(it.newSong.file, it.metadata)) {
is CoverResult.Hit -> result.cover
else -> null
val parsed = Channel<ParsedCachingItem>(Channel.UNLIMITED)
val parsedTask =
scope.tryAsyncWith(parsed, Dispatchers.IO) {
for (item in extract) {
val result =
when (item) {
is Finalized -> item
is NeedsParsing -> {
val tags = tagParser.parse(item.metadata)
val cover =
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(
it.newSong.file,
it.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.)
it.newSong.file.addedMs.resolve() ?: addingMs))
}
parsed.send(result)
}
}
val finalizedTask =
scope.tryAsyncWith(extracted, Dispatchers.IO) {
val exclude = mutableListOf<CachedSong>()
for (item in parsed) {
val result =
when (item) {
is Finalized -> item
is NeedsCaching -> {
cache.write(item.rawSong.toCachedSong())
Finalized(item.rawSong)
}
}
if (result.extracted is RawSong) {
exclude.add(result.extracted.toCachedSong())
}
it.send(result.extracted)
}
cache.cleanup(exclude)
}
.flowOn(Dispatchers.IO)
.buffer(Channel.UNLIMITED)
.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) }
return scope.merge(extractTask, parsedTask, finalizedTask)
}
private sealed interface ParsedExtractItem
@@ -20,10 +20,77 @@ package org.oxycblt.musikr.util
import java.security.MessageDigest
import java.util.UUID
import kotlin.coroutines.CoroutineContext
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.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],
* otherwise, it aliases to the unchecked dereference operator (!!). This can be used as a minor