musikr: migrate away from mimetype heuristics

This commit is contained in:
Alexander Capehart
2026-02-07 16:54:07 -07:00
parent 30455d8796
commit fa8d0d66cf
13 changed files with 228 additions and 149 deletions
+44 -5
View File
@@ -19,7 +19,9 @@
#include <jni.h>
#include <string>
#include "JInputStream.h"
#include "JClassRef.h"
#include "JMetadataBuilder.h"
#include "JObjectRef.h"
#include "util.h"
#include "taglib/fileref.h"
@@ -233,6 +235,37 @@ bool dispatchAndParse(const std::string &name, TagLib::File *file,
return false;
}
static jobject metadataResultSuccess(JNIEnv *env, jobject metadata) {
JClassRef jSuccessClass { env,
"org/oxycblt/musikr/metadata/MetadataResult$Success" };
jmethodID jInitMethod = jSuccessClass.method("<init>",
"(Lorg/oxycblt/musikr/metadata/Metadata;)V");
return env->NewObject(*jSuccessClass, jInitMethod, metadata);
}
static jobject metadataResultObject(JNIEnv *env, const char *classpath) {
JClassRef jObjectClass { env, classpath };
std::string signature = std::string("L") + classpath + ";";
jfieldID jInstanceField = env->GetStaticFieldID(*jObjectClass, "INSTANCE",
signature.c_str());
return env->GetStaticObjectField(*jObjectClass, jInstanceField);
}
static jobject metadataResultNoMetadata(JNIEnv *env) {
return metadataResultObject(env,
"org/oxycblt/musikr/metadata/MetadataResult$NoMetadata");
}
static jobject metadataResultNotAudio(JNIEnv *env) {
return metadataResultObject(env,
"org/oxycblt/musikr/metadata/MetadataResult$NotAudio");
}
static jobject metadataResultProviderFailed(JNIEnv *env) {
return metadataResultObject(env,
"org/oxycblt/musikr/metadata/MetadataResult$ProviderFailed");
}
extern "C" JNIEXPORT jobject JNICALL
Java_org_oxycblt_musikr_metadata_TagLibJNI_openNative(JNIEnv *env,
jobject /* this */,
@@ -263,7 +296,13 @@ Java_org_oxycblt_musikr_metadata_TagLibJNI_openNative(JNIEnv *env,
}
}
if (fileToUse == nullptr) {
throw std::runtime_error("Invalid or unsupported file");
delete overriddenFile;
return metadataResultNotAudio(env);
}
if (fileToUse->audioProperties() == nullptr) {
LOGE("No audio properties for %s", name.c_str());
delete overriddenFile;
return metadataResultNoMetadata(env);
}
JMetadataBuilder jBuilder {env};
jBuilder.setProperties(fileToUse->audioProperties());
@@ -271,14 +310,14 @@ Java_org_oxycblt_musikr_metadata_TagLibJNI_openNative(JNIEnv *env,
if (!dispatchAndParse(name, fileToUse, jBuilder)) {
LOGE("File format in %s is not supported by any parser.", name.c_str());
delete overriddenFile;
return nullptr;
return metadataResultNotAudio(env);
}
jobject result = jBuilder.build();
JObjectRef jMetadata {env, jBuilder.build()};
delete overriddenFile;
return result;
return metadataResultSuccess(env, *jMetadata);
} catch (std::exception &e) {
LOGE("Unable to parse metadata in %s: %s", name.c_str(), e.what());
delete overriddenFile;
return nullptr;
return metadataResultProviderFailed(env);
}
}
+20 -15
View File
@@ -34,7 +34,7 @@ import org.oxycblt.musikr.tag.parse.ParsedTags
*/
interface Cache {
/**
* Read a [CachedSong] corresponding to the given [file] from the cache. This can result in
* Read a [CachedFile] corresponding to the given [file] from the cache. This can result in
* several outcomes represented by [CacheResult].
*
* @param file the [File] to read from the cache
@@ -53,32 +53,42 @@ interface Cache {
*/
interface MutableCache : Cache {
/**
* Write a [CachedSong] to the cache.
* Write a [CachedFile] to the cache.
*
* This should commit the metadata to the repository in such a way that it can be retrieved
* later by [read] using only the [File].
*
* @param cachedSong the [CachedSong] to write to the cache
* @param cachedFile the [CachedFile] to write to the cache
*/
suspend fun write(cachedSong: CachedSong)
suspend fun write(cachedFile: CachedFile)
/**
* Cleanup the cache by removing all [CachedSong]s that are not in the provided [excluding]
* Cleanup the cache by removing all [CachedFile]s that are not in the provided [excluding]
* list.
*
* This is paramount for any long-term persistence to maintain correct Date added metadata and
* to avoid having space taken up by useless data.
*
* @param excluding a list of [CachedSong]s to exclude from cleanup, analogous to the library
* @param excluding a list of [CachedFile]s to exclude from cleanup, analogous to the library
* created by the loader this cache is used with.
*/
suspend fun cleanup(excluding: List<CachedSong>)
suspend fun cleanup(excluding: List<CachedFile>)
}
/** A cached song entry containing the data needed by the rest of the loader. */
data class CachedSong(
data class CachedFile(
/** The file this song corresponds to. */
val file: File,
val audio: Audio?,
/**
* The time the song was added to the cache. Used for date added values. Should not be used for
* cleanup since it is unlikely to be monotonic.
*/
val addedMs: Long,
)
/** Actual audio metadata if a [CachedFile] is an audio file */
data class Audio(
/** The properties of the song. */
val properties: Properties,
/** The parsed tags of the song. */
@@ -88,11 +98,6 @@ data class CachedSong(
* implementation used.
*/
val coverId: String?,
/**
* The time the song was added to the cache. Used for date added values. Should not be used for
* cleanup since it is unlikely to be monotonic.
*/
val addedMs: Long,
)
/** A result of a cache lookup. */
@@ -100,9 +105,9 @@ sealed interface CacheResult {
/**
* A cache entry was found.
*
* @param song the [CachedSong] that was found.
* @param file the [CachedFile] that was found.
*/
data class Hit(val song: CachedSong) : CacheResult
data class Hit(val file: CachedFile) : CacheResult
/**
* A cache entry was not found.
@@ -36,7 +36,7 @@ import org.oxycblt.musikr.tag.Date
import org.oxycblt.musikr.util.correctWhitespace
import org.oxycblt.musikr.util.splitEscaped
@Database(entities = [CachedSongData::class], version = 67, exportSchema = false)
@Database(entities = [CachedFileData::class], version = 70, exportSchema = false)
internal abstract class CacheDatabase : RoomDatabase() {
abstract fun readDao(): CacheReadDao
@@ -56,12 +56,12 @@ internal abstract class CacheDatabase : RoomDatabase() {
@Dao
internal interface CacheReadDao {
@Query("SELECT * FROM CachedSongData") suspend fun selectAllSongs(): List<CachedSongData>
@Query("SELECT * FROM CachedFileData") suspend fun selectAllSongs(): List<CachedFileData>
}
@Dao
internal interface CacheWriteDao {
@Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun updateSong(data: CachedSongData)
@Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun updateSong(data: CachedFileData)
@Transaction
suspend fun deleteExcludingUris(uris: Set<String>) {
@@ -71,22 +71,22 @@ internal interface CacheWriteDao {
}
}
@Query("SELECT uri FROM CachedSongData") suspend fun selectAllUris(): List<String>
@Query("SELECT uri FROM CachedFileData") suspend fun selectAllUris(): List<String>
@Query("DELETE FROM CachedSongData WHERE uri IN (:uris)")
@Query("DELETE FROM CachedFileData WHERE uri IN (:uris)")
suspend fun deleteExcludingUriChunk(uris: List<String>)
}
@Entity
@TypeConverters(CachedSongData.Converters::class)
internal data class CachedSongData(
@TypeConverters(CachedFileData.Converters::class)
internal data class CachedFileData(
@PrimaryKey val uri: Uri,
val modifiedMs: Long,
val addedMs: Long,
val mimeType: String,
val durationMs: Long,
val bitrateKbps: Int,
val sampleRateHz: Int,
val mimeType: String?,
val durationMs: Long?,
val bitrateKbps: Int?,
val sampleRateHz: Int?,
val musicBrainzId: String?,
val name: String?,
val sortName: String?,
@@ -97,14 +97,14 @@ internal data class CachedSongData(
val albumMusicBrainzId: String?,
val albumName: String?,
val albumSortName: String?,
val releaseTypes: List<String>,
val artistMusicBrainzIds: List<String>,
val artistNames: List<String>,
val artistSortNames: List<String>,
val albumArtistMusicBrainzIds: List<String>,
val albumArtistNames: List<String>,
val albumArtistSortNames: List<String>,
val genreNames: List<String>,
val releaseTypes: List<String>?,
val artistMusicBrainzIds: List<String>?,
val artistNames: List<String>?,
val artistSortNames: List<String>?,
val albumArtistMusicBrainzIds: List<String>?,
val albumArtistNames: List<String>?,
val albumArtistSortNames: List<String>?,
val genreNames: List<String>?,
val replayGainTrackAdjustment: Float?,
val replayGainAlbumAdjustment: Float?,
val coverId: String?,
+69 -64
View File
@@ -22,9 +22,10 @@ import android.content.Context
import android.net.Uri
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import org.oxycblt.musikr.cache.Audio
import org.oxycblt.musikr.cache.Cache
import org.oxycblt.musikr.cache.CacheResult
import org.oxycblt.musikr.cache.CachedSong
import org.oxycblt.musikr.cache.CachedFile
import org.oxycblt.musikr.cache.MutableCache
import org.oxycblt.musikr.fs.File
import org.oxycblt.musikr.metadata.Properties
@@ -36,7 +37,7 @@ import org.oxycblt.musikr.tag.parse.ParsedTags
* Create an instance with [from].
*/
class DBCache private constructor(private val readDao: CacheReadDao) : Cache {
private var mapping: Map<Uri, CachedSongData>? = null
private var mapping: Map<Uri, CachedFileData>? = null
private val mappingLock = Mutex()
override suspend fun read(file: File): CacheResult {
@@ -49,38 +50,42 @@ class DBCache private constructor(private val readDao: CacheReadDao) : Cache {
return CacheResult.Stale(file, dbSong.addedMs)
}
val song =
CachedSong(
CachedFile(
file,
Properties(
dbSong.mimeType,
dbSong.durationMs,
dbSong.bitrateKbps,
dbSong.sampleRateHz,
),
ParsedTags(
musicBrainzId = dbSong.musicBrainzId,
name = dbSong.name,
sortName = dbSong.sortName,
durationMs = dbSong.durationMs,
track = dbSong.track,
disc = dbSong.disc,
subtitle = dbSong.subtitle,
date = dbSong.date,
albumMusicBrainzId = dbSong.albumMusicBrainzId,
albumName = dbSong.albumName,
albumSortName = dbSong.albumSortName,
releaseTypes = dbSong.releaseTypes,
artistMusicBrainzIds = dbSong.artistMusicBrainzIds,
artistNames = dbSong.artistNames,
artistSortNames = dbSong.artistSortNames,
albumArtistMusicBrainzIds = dbSong.albumArtistMusicBrainzIds,
albumArtistNames = dbSong.albumArtistNames,
albumArtistSortNames = dbSong.albumArtistSortNames,
genreNames = dbSong.genreNames,
replayGainTrackAdjustment = dbSong.replayGainTrackAdjustment,
replayGainAlbumAdjustment = dbSong.replayGainAlbumAdjustment,
),
coverId = dbSong.coverId,
dbSong.mimeType?.let {
Audio(
Properties(
dbSong.mimeType,
dbSong.durationMs!!,
dbSong.bitrateKbps!!,
dbSong.sampleRateHz!!,
),
ParsedTags(
musicBrainzId = dbSong.musicBrainzId,
name = dbSong.name,
sortName = dbSong.sortName,
durationMs = dbSong.durationMs,
track = dbSong.track,
disc = dbSong.disc,
subtitle = dbSong.subtitle,
date = dbSong.date,
albumMusicBrainzId = dbSong.albumMusicBrainzId,
albumName = dbSong.albumName,
albumSortName = dbSong.albumSortName,
releaseTypes = dbSong.releaseTypes!!,
artistMusicBrainzIds = dbSong.artistMusicBrainzIds!!,
artistNames = dbSong.artistNames!!,
artistSortNames = dbSong.artistSortNames!!,
albumArtistMusicBrainzIds = dbSong.albumArtistMusicBrainzIds!!,
albumArtistNames = dbSong.albumArtistNames!!,
albumArtistSortNames = dbSong.albumArtistSortNames!!,
genreNames = dbSong.genreNames!!,
replayGainTrackAdjustment = dbSong.replayGainTrackAdjustment,
replayGainAlbumAdjustment = dbSong.replayGainAlbumAdjustment,
),
coverId = dbSong.coverId,
)
},
addedMs = dbSong.addedMs,
)
return CacheResult.Hit(song)
@@ -112,42 +117,42 @@ private constructor(private val inner: DBCache, private val writeDao: CacheWrite
MutableCache {
override suspend fun read(file: File) = inner.read(file)
override suspend fun write(cachedSong: CachedSong) {
override suspend fun write(cachedFile: CachedFile) {
val dbSong =
CachedSongData(
uri = cachedSong.file.uri,
modifiedMs = cachedSong.file.modifiedMs,
addedMs = cachedSong.addedMs,
mimeType = cachedSong.properties.mimeType,
durationMs = cachedSong.properties.durationMs,
bitrateKbps = cachedSong.properties.bitrateKbps,
sampleRateHz = cachedSong.properties.sampleRateHz,
musicBrainzId = cachedSong.tags.musicBrainzId,
name = cachedSong.tags.name,
sortName = cachedSong.tags.sortName,
track = cachedSong.tags.track,
disc = cachedSong.tags.disc,
subtitle = cachedSong.tags.subtitle,
date = cachedSong.tags.date,
albumMusicBrainzId = cachedSong.tags.albumMusicBrainzId,
albumName = cachedSong.tags.albumName,
albumSortName = cachedSong.tags.albumSortName,
releaseTypes = cachedSong.tags.releaseTypes,
artistMusicBrainzIds = cachedSong.tags.artistMusicBrainzIds,
artistNames = cachedSong.tags.artistNames,
artistSortNames = cachedSong.tags.artistSortNames,
albumArtistMusicBrainzIds = cachedSong.tags.albumArtistMusicBrainzIds,
albumArtistNames = cachedSong.tags.albumArtistNames,
albumArtistSortNames = cachedSong.tags.albumArtistSortNames,
genreNames = cachedSong.tags.genreNames,
replayGainTrackAdjustment = cachedSong.tags.replayGainTrackAdjustment,
replayGainAlbumAdjustment = cachedSong.tags.replayGainAlbumAdjustment,
coverId = cachedSong.coverId,
CachedFileData(
uri = cachedFile.file.uri,
modifiedMs = cachedFile.file.modifiedMs,
addedMs = cachedFile.addedMs,
mimeType = cachedFile.audio?.properties?.mimeType,
durationMs = cachedFile.audio?.properties?.durationMs,
bitrateKbps = cachedFile.audio?.properties?.bitrateKbps,
sampleRateHz = cachedFile.audio?.properties?.sampleRateHz,
musicBrainzId = cachedFile.audio?.tags?.musicBrainzId,
name = cachedFile.audio?.tags?.name,
sortName = cachedFile.audio?.tags?.sortName,
track = cachedFile.audio?.tags?.track,
disc = cachedFile.audio?.tags?.disc,
subtitle = cachedFile.audio?.tags?.subtitle,
date = cachedFile.audio?.tags?.date,
albumMusicBrainzId = cachedFile.audio?.tags?.albumMusicBrainzId,
albumName = cachedFile.audio?.tags?.albumName,
albumSortName = cachedFile.audio?.tags?.albumSortName,
releaseTypes = cachedFile.audio?.tags?.releaseTypes,
artistMusicBrainzIds = cachedFile.audio?.tags?.artistMusicBrainzIds,
artistNames = cachedFile.audio?.tags?.artistNames,
artistSortNames = cachedFile.audio?.tags?.artistSortNames,
albumArtistMusicBrainzIds = cachedFile.audio?.tags?.albumArtistMusicBrainzIds,
albumArtistNames = cachedFile.audio?.tags?.albumArtistNames,
albumArtistSortNames = cachedFile.audio?.tags?.albumArtistSortNames,
genreNames = cachedFile.audio?.tags?.genreNames,
replayGainTrackAdjustment = cachedFile.audio?.tags?.replayGainTrackAdjustment,
replayGainAlbumAdjustment = cachedFile.audio?.tags?.replayGainAlbumAdjustment,
coverId = cachedFile.audio?.coverId,
)
writeDao.updateSong(dbSong)
}
override suspend fun cleanup(excluding: List<CachedSong>) {
override suspend fun cleanup(excluding: List<CachedFile>) {
writeDao.deleteExcludingUris(excluding.mapTo(mutableSetOf()) { it.file.uri.toString() })
}
@@ -145,7 +145,7 @@ class MutableFSCovers(private val context: Context) : MutableCovers<FDCover> {
}
}
private data class FolderCoverImpl(private val context: Context, private val uri: Uri) : FDCover {
private class FolderCoverImpl(private val context: Context, private val uri: Uri) : FDCover {
override val id = PREFIX + uri.toString()
// Implies that client will manage freeing the resources themselves.
@@ -157,4 +157,12 @@ private data class FolderCoverImpl(private val context: Context, private val uri
@SuppressLint("Recycle")
override suspend fun fd(): ParcelFileDescriptor? =
withContext(Dispatchers.IO) { context.contentResolver.openFileDescriptor(uri, "r") }
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is FolderCoverImpl) return false
return id == other.id
}
override fun hashCode(): Int = id.hashCode()
}
@@ -26,7 +26,7 @@ import kotlinx.coroutines.withContext
import org.oxycblt.musikr.fs.File
internal interface MetadataExtractor {
suspend fun extract(deviceFile: File): Metadata?
suspend fun extract(deviceFile: File): MetadataResult
companion object {
fun from(context: Context): MetadataExtractor =
@@ -34,13 +34,23 @@ internal interface MetadataExtractor {
}
}
sealed interface MetadataResult {
data class Success(val metadata: Metadata?) : MetadataResult
data object NoMetadata : MetadataResult
data object NotAudio : MetadataResult
data object ProviderFailed : MetadataResult
}
private class MetadataExtractorImpl(private val contentResolver: ContentResolver) :
MetadataExtractor {
override suspend fun extract(deviceFile: File): Metadata? =
override suspend fun extract(deviceFile: File): MetadataResult =
withContext(Dispatchers.IO) {
contentResolver.openFileDescriptor(deviceFile.uri, "r")?.use { fd ->
val fis = FileInputStream(fd.fileDescriptor)
TagLibJNI.open(deviceFile, fis).also { fis.close() }
}
} ?: MetadataResult.ProviderFailed
}
}
@@ -31,12 +31,12 @@ internal object TagLibJNI {
*
* Note: This method is blocking and should be handled as such if calling from a coroutine.
*/
fun open(deviceFile: File, fis: FileInputStream): Metadata? {
fun open(deviceFile: File, fis: FileInputStream): MetadataResult {
val inputStream = NativeInputStream(deviceFile, fis)
val tag = openNative(inputStream)
inputStream.close()
return tag
}
private external fun openNative(inputStream: NativeInputStream): Metadata?
private external fun openNative(inputStream: NativeInputStream): MetadataResult
}
@@ -59,9 +59,9 @@ private class EvaluateStepImpl(
when (extracted) {
is RawSong -> builder.add(tagInterpreter.interpret(extracted))
is RawPlaylist -> builder.add(playlistInterpreter.interpret(extracted.file))
is NotAudio -> {}
is InvalidSong -> {}
}
builder
}
val graph = builder.build()
@@ -26,12 +26,10 @@ import kotlinx.coroutines.channels.Channel
import org.oxycblt.musikr.Config
import org.oxycblt.musikr.Storage
import org.oxycblt.musikr.cache.CacheResult
import org.oxycblt.musikr.cache.CachedSong
import org.oxycblt.musikr.covers.Cover
import org.oxycblt.musikr.cache.CachedFile
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.mapParallel
import org.oxycblt.musikr.util.merge
import org.oxycblt.musikr.util.tryAsyncWith
@@ -56,12 +54,8 @@ private class ExploreStepImpl(private val fs: FS, private val storage: Storage)
val classified = Channel<Classified>(Channel.UNLIMITED)
val classifiedTask =
scope.mapParallel(PARALLELISM, files, classified, Dispatchers.IO) { file ->
if (!file.mimeType.startsWith("audio/") && file.mimeType != M3U.MIME_TYPE) {
return@mapParallel null
}
val cacheResult = storage.cache.read(file)
when (cacheResult) {
is CacheResult.Hit -> NeedsCover(cacheResult.song)
when (val cacheResult = storage.cache.read(file)) {
is CacheResult.Hit -> NeedsHydration(cacheResult.file)
is CacheResult.Stale -> Finalized(NewSong(cacheResult.file))
is CacheResult.Miss -> Finalized(NewSong(cacheResult.file))
}
@@ -72,16 +66,27 @@ private class ExploreStepImpl(private val fs: FS, private val storage: Storage)
scope.mapParallel(PARALLELISM, classified, finalized, Dispatchers.IO) { item ->
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))
}
is NeedsHydration -> {
val audio = item.cachedFile.audio ?: return@mapParallel Finalized(NotAudio)
val coverId =
when (
val result = audio.coverId?.let { id -> storage.covers.obtain(id) }
) {
is CoverResult.Hit -> result.cover
is CoverResult.Miss ->
return@mapParallel Finalized(NewSong(item.cachedFile.file))
null -> null
}
Finalized(
RawSong(
item.cachedFile.file,
audio.properties,
audio.tags,
coverId,
item.cachedFile.addedMs,
)
)
}
}
}
@@ -109,13 +114,10 @@ private class ExploreStepImpl(private val fs: FS, private val storage: Storage)
private sealed interface Classified
private data class NeedsCover(val cachedSong: CachedSong) : Classified
private data class NeedsHydration(val cachedFile: CachedFile) : Classified
private data class Finalized(val explored: Explored) : Classified
private fun CachedSong.toRawSong(cover: Cover?) =
RawSong(file, properties, tags, cover, addedMs)
private companion object {
const val PARALLELISM = 8
}
@@ -24,13 +24,15 @@ import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import org.oxycblt.musikr.Config
import org.oxycblt.musikr.cache.CachedSong
import org.oxycblt.musikr.cache.Audio
import org.oxycblt.musikr.cache.CachedFile
import org.oxycblt.musikr.cache.MutableCache
import org.oxycblt.musikr.covers.Cover
import org.oxycblt.musikr.covers.CoverResult
import org.oxycblt.musikr.covers.MutableCovers
import org.oxycblt.musikr.metadata.Metadata
import org.oxycblt.musikr.metadata.MetadataExtractor
import org.oxycblt.musikr.metadata.MetadataResult
import org.oxycblt.musikr.tag.parse.TagParser
import org.oxycblt.musikr.util.mapParallel
import org.oxycblt.musikr.util.merge
@@ -73,10 +75,16 @@ private class ExtractStepImpl(
is RawSong -> Finalized(item)
is RawPlaylist -> Finalized(item)
is NewSong -> {
val metadata = metadataExtractor.extract(item.file)
if (metadata != null) NeedsParsing(item, metadata)
else Finalized(InvalidSong)
when (val result = metadataExtractor.extract(item.file)) {
is MetadataResult.Success ->
result.metadata?.let { metadata -> NeedsParsing(item, metadata) }
?: Finalized(InvalidSong)
MetadataResult.NoMetadata -> Finalized(InvalidSong)
MetadataResult.NotAudio -> Finalized(NotAudio)
MetadataResult.ProviderFailed -> Finalized(InvalidSong)
}
}
is NotAudio -> Finalized(NotAudio)
}
}
val parsed = Channel<ParsedCachingItem>(Channel.UNLIMITED)
@@ -113,18 +121,18 @@ private class ExtractStepImpl(
}
val finalizedTask =
scope.tryAsyncWith(extracted, Dispatchers.IO) {
val exclude = mutableListOf<CachedSong>()
val exclude = mutableListOf<CachedFile>()
for (item in parsed) {
val result =
when (item) {
is Finalized -> item
is NeedsCaching -> {
cache.write(item.rawSong.toCachedSong())
cache.write(item.rawSong.toCachedFile())
Finalized(item.rawSong)
}
}
if (result.extracted is RawSong) {
exclude.add(result.extracted.toCachedSong())
exclude.add(result.extracted.toCachedFile())
}
it.send(result.extracted)
}
@@ -145,7 +153,8 @@ private class ExtractStepImpl(
private data class Finalized(val extracted: Extracted) : ParsedExtractItem, ParsedCachingItem
private fun RawSong.toCachedSong() = CachedSong(file, properties, tags, cover?.id, addedMs)
private fun RawSong.toCachedFile() =
CachedFile(file, audio = Audio(properties, tags, cover?.id), addedMs)
private companion object {
const val PARALLELISM = 8
@@ -46,6 +46,8 @@ internal sealed interface Extracted : PipelineItem {
internal data object InvalidSong : Extracted.Invalid
internal data object NotAudio : Explored.Known, Extracted.Valid
internal data class RawPlaylist(val file: PlaylistFile) : Explored.Known, Extracted.Valid
internal data class RawSong(
@@ -79,7 +79,7 @@ fun <T, R> CoroutineScope.mapParallel(
input: Channel<T>,
output: Channel<R>,
context: CoroutineContext = Dispatchers.Default,
block: suspend (T) -> R?,
block: suspend (T) -> R,
): Deferred<Result<Unit>> {
return tryAsync(context) {
val deferreds = ArrayList<Deferred<Result<Unit>>>()
@@ -87,14 +87,13 @@ fun <T, R> CoroutineScope.mapParallel(
val deferred =
tryAsync(context) {
for (item in input) {
block(item)?.let { output.send(it) }
block(item).let { output.send(it) }
}
}
deferreds.add(deferred)
}
deferreds.tryAwaitAll()
output.close()
Unit
}
}