diff --git a/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt b/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt index 77ed3db41..bd15fd2b9 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt @@ -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(Channel.UNLIMITED) + val exploredTask = exploreStep.explore(this, exploredChannel) + val trackedExploredChannel = Channel(Channel.UNLIMITED) + val trackedExploredTask = + tryAsyncWith(trackedExploredChannel, Dispatchers.Main) { + for (item in exploredChannel) { + explored++ + onProgress(IndexingProgress.Songs(loaded, explored)) + trackedExploredChannel.send(item) + } + } + val extractedChannel = Channel(Channel.UNLIMITED) + val extractedTask = extractStep.extract(this, trackedExploredChannel, extractedChannel) + val trackedExtractedChannel = Channel(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) } } diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/FS.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/FS.kt index 1171cd961..46577fe0e 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/FS.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/FS.kt @@ -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 + suspend fun explore(files: Channel): Deferred> fun track(): Flow } diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/mediastore/MediaStore.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/mediastore/MediaStore.kt index 3cb5b1437..22d8b8168 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/mediastore/MediaStore.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/mediastore/MediaStore.kt @@ -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 = flow { - val projection = BASE_PROJECTION + pathInterpreterFactory.projection - var selector = BASE_SELECTOR - val args = mutableListOf() + override suspend fun explore(files: Channel): Deferred> = coroutineScope { + tryAsyncWith(files, Dispatchers.IO) { + val projection = BASE_PROJECTION + pathInterpreterFactory.projection + var selector = BASE_SELECTOR + val args = mutableListOf() - // 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() + + 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() - - 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 = callbackFlow { diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/saf/SAF.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/saf/SAF.kt index 937998ec4..7ec48ff45 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/saf/SAF.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/saf/SAF.kt @@ -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 = - 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): Deferred> = 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 = callbackFlow { val observers = mutableListOf() @@ -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?, - exclude: Set - ): Flow = flow { - // Make a kotlin future - val uri = DocumentsContract.buildChildDocumentsUriUsingTree(rootUri, treeDocumentId) - val directoryDeferred = CompletableDeferred() - val recursive = mutableListOf>() - val children = mutableListOf() - 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, + files: Channel + ): Deferred> = + tryAsync(Dispatchers.IO) { + // Make a kotlin future + val uri = DocumentsContract.buildChildDocumentsUriUsingTree(rootUri, treeDocumentId) + val directoryDeferred = CompletableDeferred() + val recursive = mutableListOf>>() + val children = mutableListOf() + 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, diff --git a/musikr/src/main/java/org/oxycblt/musikr/pipeline/EvaluateStep.kt b/musikr/src/main/java/org/oxycblt/musikr/pipeline/EvaluateStep.kt index 0a417d5da..fa0254e6b 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/pipeline/EvaluateStep.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/pipeline/EvaluateStep.kt @@ -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): MutableLibrary + suspend fun evaluate(extractedMusic: Channel): 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): MutableLibrary = - extractedMusic - .filterIsInstance() - .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): 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) + } } diff --git a/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExploreStep.kt b/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExploreStep.kt index 951b73e68..879ba474a 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExploreStep.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExploreStep.kt @@ -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 + suspend fun explore(scope: CoroutineScope, explored: Channel): Deferred> 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 { - 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 + ): Deferred> { + val files = Channel(Channel.UNLIMITED) + val filesTask = fs.explore(files) + + val classified = Channel(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(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(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) diff --git a/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExtractStep.kt b/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExtractStep.kt index 85ee35253..040113045 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExtractStep.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExtractStep.kt @@ -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): Flow + suspend fun extract( + scope: CoroutineScope, + explored: Channel, + extracted: Channel + ): Deferred> companion object { fun from(context: Context, config: Config): ExtractStep = @@ -55,72 +59,81 @@ private class ExtractStepImpl( private val cache: MutableCache, private val covers: MutableCovers ) : ExtractStep { - override fun extract(nodes: Flow): Flow { + override suspend fun extract( + scope: CoroutineScope, + explored: Channel, + extracted: Channel + ): Deferred> { val addingMs = System.currentTimeMillis() - val exclude = mutableListOf() - 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(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(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() + 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 diff --git a/musikr/src/main/java/org/oxycblt/musikr/util/LangUtil.kt b/musikr/src/main/java/org/oxycblt/musikr/util/LangUtil.kt index a1b361370..587eab28b 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/util/LangUtil.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/util/LangUtil.kt @@ -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> = async { + try { + block() + Result.success(Unit) + } catch (e: Throwable) { + Result.failure(e) + } +} + +fun CoroutineScope.tryAsyncWith( + channel: Channel, + context: CoroutineContext, + block: suspend (Channel) -> Unit, +): Deferred> = + async(context) { + try { + block(channel) + channel.close() + Result.success(Unit) + } catch (e: Throwable) { + channel.close(e) + Result.failure(e) + } + } + +fun CoroutineScope.tryParWith( + n: Int, + channel: Channel, + output: Channel, + context: CoroutineContext = Dispatchers.Default, + block: suspend (T) -> R, +): Deferred> { + return tryAsync(context) { + val deferreds = ArrayList>>() + 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>>.tryAwaitAll() = awaitAll().forEach { it.getOrThrow() } + +fun CoroutineScope.merge(vararg deferreds: Deferred>): Deferred> = + 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