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,7 +55,8 @@ 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 {
tryAsyncWith(files, Dispatchers.IO) {
val projection = BASE_PROJECTION + pathInterpreterFactory.projection val projection = BASE_PROJECTION + pathInterpreterFactory.projection
var selector = BASE_SELECTOR var selector = BASE_SELECTOR
val args = mutableListOf<String>() val args = mutableListOf<String>()
@@ -91,14 +95,17 @@ private constructor(
selector, selector,
args.toTypedArray()) { cursor -> args.toTypedArray()) { cursor ->
val pathInterpreter = pathInterpreterFactory.wrap(cursor) val pathInterpreter = pathInterpreterFactory.wrap(cursor)
val idIndex = cursor.getColumnIndexOrThrow(AOSPMediaStore.Audio.AudioColumns._ID) val idIndex =
cursor.getColumnIndexOrThrow(AOSPMediaStore.Audio.AudioColumns._ID)
val mimeTypeIndex = val mimeTypeIndex =
cursor.getColumnIndexOrThrow(AOSPMediaStore.Audio.AudioColumns.MIME_TYPE) cursor.getColumnIndexOrThrow(AOSPMediaStore.Audio.AudioColumns.MIME_TYPE)
val sizeIndex = cursor.getColumnIndexOrThrow(AOSPMediaStore.Audio.AudioColumns.SIZE) val sizeIndex =
cursor.getColumnIndexOrThrow(AOSPMediaStore.Audio.AudioColumns.SIZE)
val dateAddedIndex = val dateAddedIndex =
cursor.getColumnIndexOrThrow(AOSPMediaStore.Audio.AudioColumns.DATE_ADDED) cursor.getColumnIndexOrThrow(AOSPMediaStore.Audio.AudioColumns.DATE_ADDED)
val dateModifiedIndex = val dateModifiedIndex =
cursor.getColumnIndexOrThrow(AOSPMediaStore.Audio.AudioColumns.DATE_MODIFIED) cursor.getColumnIndexOrThrow(
AOSPMediaStore.Audio.AudioColumns.DATE_MODIFIED)
while (cursor.moveToNext()) { while (cursor.moveToNext()) {
val path = pathInterpreter.extract() ?: continue val path = pathInterpreter.extract() ?: continue
@@ -109,7 +116,8 @@ private constructor(
AOSPMediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id.toString()) AOSPMediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id.toString())
val mimeType = cursor.getStringOrNull(mimeTypeIndex) ?: "audio/*" val mimeType = cursor.getStringOrNull(mimeTypeIndex) ?: "audio/*"
val size = cursor.getLong(sizeIndex) val size = cursor.getLong(sizeIndex)
val dateAdded = cursor.getLong(dateAddedIndex) * 1000 // Convert to milliseconds val dateAdded =
cursor.getLong(dateAddedIndex) * 1000 // Convert to milliseconds
val dateModified = val dateModified =
cursor.getLong(dateModifiedIndex) * 1000 // Convert to milliseconds cursor.getLong(dateModifiedIndex) * 1000 // Convert to milliseconds
@@ -125,8 +133,8 @@ private constructor(
parent = null) parent = null)
allFiles.add(deviceFile) allFiles.add(deviceFile)
emit(deviceFile) it.send(deviceFile)
yield() }
} }
} }
} }
@@ -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,14 +54,20 @@ 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) {
query.source
.map { location ->
exploreDirectoryImpl( exploreDirectoryImpl(
location.uri, location.uri,
DocumentsContract.getTreeDocumentId(location.uri), DocumentsContract.getTreeDocumentId(location.uri),
location.path, location.path,
null, null,
query.exclude.mapTo(mutableSetOf()) { it.path }) query.exclude.mapTo(mutableSetOf()) { it.path },
files)
}
.tryAwaitAll()
}
} }
override fun track(): Flow<FSUpdate> = callbackFlow { override fun track(): Flow<FSUpdate> = callbackFlow {
@@ -76,17 +84,19 @@ 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>
): Deferred<Result<Unit>> =
tryAsync(Dispatchers.IO) {
// Make a kotlin future // Make a kotlin future
val uri = DocumentsContract.buildChildDocumentsUriUsingTree(rootUri, treeDocumentId) val uri = DocumentsContract.buildChildDocumentsUriUsingTree(rootUri, treeDocumentId)
val directoryDeferred = CompletableDeferred<Directory>() val directoryDeferred = CompletableDeferred<Directory>()
val recursive = mutableListOf<Flow<File>>() val recursive = mutableListOf<Deferred<Result<Unit>>>()
val children = mutableListOf<File>() val children = mutableListOf<File>()
contentResolver.useQuery(uri, PROJECTION) { cursor -> contentResolver.useQuery(uri, PROJECTION) { cursor ->
val childUriIndex = val childUriIndex =
@@ -121,7 +131,8 @@ private constructor(
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(
rootUri, childId, newPath, directoryDeferred, exclude, files))
} else { } else {
val size = cursor.getLong(sizeIndex) val size = cursor.getLong(sizeIndex)
val file = val file =
@@ -139,12 +150,12 @@ private constructor(
NullAddedMs NullAddedMs
}) })
children.add(file) children.add(file)
emit(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( data class Query(
@@ -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 -> graphBuilder.add(tagInterpreter.interpret(extracted)) is RawSong -> builder.add(tagInterpreter.interpret(extracted))
is RawPlaylist -> is RawPlaylist -> builder.add(playlistInterpreter.interpret(extracted.file))
graphBuilder.add(playlistInterpreter.interpret(extracted.file)) is InvalidSong -> {}
} }
graphBuilder builder
}
return libraryFactory.create(builder.build(), storedPlaylists, playlistInterpreter)
} }
.let { libraryFactory.create(it.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) {
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)))
} }
} }
.flowOn(Dispatchers.IO) }
.buffer(Channel.UNLIMITED) }
.distributedMap(n = 8, on = Dispatchers.IO, buffer = Channel.UNLIMITED) {
when (it) { val finalized = Channel<Explored>(Channel.UNLIMITED)
is Finalized -> it val exploredTask =
scope.tryAsyncWith(finalized, Dispatchers.IO) {
for (item in classified) {
val result =
when (item) {
is Finalized -> item
is NeedsCover -> { is NeedsCover -> {
when (val coverResult = when (val coverResult =
it.cachedSong.coverId?.let { id -> storage.covers.obtain(id) }) { item.cachedSong.coverId?.let { id ->
storage.covers.obtain(id)
}) {
is CoverResult.Hit -> is CoverResult.Hit ->
Finalized(it.cachedSong.toRawSong(coverResult.cover)) Finalized(item.cachedSong.toRawSong(coverResult.cover))
null -> Finalized(it.cachedSong.toRawSong(null)) null -> Finalized(item.cachedSong.toRawSong(null))
else -> Finalized(NewSong(it.cachedSong.file)) 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)
} }
.map { it.explored }
.flowOn(Dispatchers.IO)
.buffer(Channel.UNLIMITED),
flow { emitAll(storage.storedPlaylists.read().asFlow()) }
.map { RawPlaylist(it) }
.flowOn(Dispatchers.IO)
.buffer(Channel.UNLIMITED))
} }
private sealed interface InternalExploreItem val mergeTask =
scope.tryAsyncWith(explored, Dispatchers.Main) {
for (item in finalized) {
it.send(item)
}
for (playlist in playlists) {
it.send(playlist)
}
}
private data class NeedsCover(val cachedSong: CachedSong) : InternalExploreItem return scope.merge(filesTask, classifiedTask, exploredTask, playlistsTask, mergeTask)
}
private data class Finalized(val explored: Explored) : InternalExploreItem private sealed interface Classified
private data class NeedsCover(val cachedSong: CachedSong) : Classified
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 =
when (item) {
is Finalized -> item
is NeedsParsing -> { is NeedsParsing -> {
val tags = tagParser.parse(it.metadata) val tags = tagParser.parse(item.metadata)
val cover = val cover =
when (val result = covers.create(it.newSong.file, it.metadata)) { when (val result =
covers.create(item.newSong.file, item.metadata)) {
is CoverResult.Hit -> result.cover is CoverResult.Hit -> result.cover
else -> null else -> null
} }
NeedsCaching( NeedsCaching(
RawSong( RawSong(
it.newSong.file, item.newSong.file,
it.metadata.properties, item.metadata.properties,
tags, tags,
cover, cover,
// The thing about date added is that it's resolution can actually // The thing about date added is that it's resolution can
// be expensive in some modes (ex. saf backend), so we resolve this // actually be expensive in some modes (ex. saf backend), so
// by // we resolve this by moving date added extraction as an
// moving date added extraction as an extraction operation rather // extraction operation rather than doing the redundant work
// than doing the redundant work during exploration (well, kind of, // during exploration (well, kind of, MediaStore's date
// MediaStore's date added query is basically free, it's only saf // added query is basically free, it's only saf that has
// that has it's slow hacky workaround that we must accommodate // it's slow hacky workaround that we must accommodate
// here.) // here.)
it.newSong.file.addedMs.resolve() ?: addingMs)) item.newSong.file.addedMs.resolve() ?: addingMs))
} }
} }
parsed.send(result)
} }
.flowOn(Dispatchers.IO) }
.buffer(Channel.UNLIMITED) val finalizedTask =
.distributedMap(on = Dispatchers.IO, n = 8, buffer = Channel.UNLIMITED) { scope.tryAsyncWith(extracted, Dispatchers.IO) {
when (it) { val exclude = mutableListOf<CachedSong>()
is Finalized -> it for (item in parsed) {
val result =
when (item) {
is Finalized -> item
is NeedsCaching -> { is NeedsCaching -> {
cache.write(it.rawSong.toCachedSong()) cache.write(item.rawSong.toCachedSong())
Finalized(it.rawSong) Finalized(item.rawSong)
} }
} }
if (result.extracted is RawSong) {
exclude.add(result.extracted.toCachedSong())
} }
.map { it.send(result.extracted)
if (it.extracted is RawSong) {
exclude.add(it.extracted.toCachedSong())
} }
it.extracted cache.cleanup(exclude)
} }
.flowOn(Dispatchers.IO)
.buffer(Channel.UNLIMITED) return scope.merge(extractTask, parsedTask, finalizedTask)
.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