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
@@ -19,23 +19,23 @@
package org.oxycblt.auxio.music.shim package org.oxycblt.auxio.music.shim
import org.oxycblt.musikr.cache.CacheResult 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.cache.MutableCache
import org.oxycblt.musikr.fs.File import org.oxycblt.musikr.fs.File
class WriteOnlyMutableCache(private val inner: MutableCache) : MutableCache { class WriteOnlyMutableCache(private val inner: MutableCache) : MutableCache {
override suspend fun read(file: File): CacheResult { override suspend fun read(file: File): CacheResult {
return when (val result = inner.read(file)) { return when (val result = inner.read(file)) {
is CacheResult.Hit -> CacheResult.Stale(file, result.song.addedMs) is CacheResult.Hit -> CacheResult.Stale(file, result.file.addedMs)
else -> result else -> result
} }
} }
override suspend fun write(cachedSong: CachedSong) { override suspend fun write(cachedFile: CachedFile) {
inner.write(cachedSong) inner.write(cachedFile)
} }
override suspend fun cleanup(excluding: List<CachedSong>) { override suspend fun cleanup(excluding: List<CachedFile>) {
inner.cleanup(excluding) inner.cleanup(excluding)
} }
} }
+44 -5
View File
@@ -19,7 +19,9 @@
#include <jni.h> #include <jni.h>
#include <string> #include <string>
#include "JInputStream.h" #include "JInputStream.h"
#include "JClassRef.h"
#include "JMetadataBuilder.h" #include "JMetadataBuilder.h"
#include "JObjectRef.h"
#include "util.h" #include "util.h"
#include "taglib/fileref.h" #include "taglib/fileref.h"
@@ -233,6 +235,37 @@ bool dispatchAndParse(const std::string &name, TagLib::File *file,
return false; 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 extern "C" JNIEXPORT jobject JNICALL
Java_org_oxycblt_musikr_metadata_TagLibJNI_openNative(JNIEnv *env, Java_org_oxycblt_musikr_metadata_TagLibJNI_openNative(JNIEnv *env,
jobject /* this */, jobject /* this */,
@@ -263,7 +296,13 @@ Java_org_oxycblt_musikr_metadata_TagLibJNI_openNative(JNIEnv *env,
} }
} }
if (fileToUse == nullptr) { 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}; JMetadataBuilder jBuilder {env};
jBuilder.setProperties(fileToUse->audioProperties()); jBuilder.setProperties(fileToUse->audioProperties());
@@ -271,14 +310,14 @@ Java_org_oxycblt_musikr_metadata_TagLibJNI_openNative(JNIEnv *env,
if (!dispatchAndParse(name, fileToUse, jBuilder)) { if (!dispatchAndParse(name, fileToUse, jBuilder)) {
LOGE("File format in %s is not supported by any parser.", name.c_str()); LOGE("File format in %s is not supported by any parser.", name.c_str());
delete overriddenFile; delete overriddenFile;
return nullptr; return metadataResultNotAudio(env);
} }
jobject result = jBuilder.build(); JObjectRef jMetadata {env, jBuilder.build()};
delete overriddenFile; delete overriddenFile;
return result; return metadataResultSuccess(env, *jMetadata);
} catch (std::exception &e) { } catch (std::exception &e) {
LOGE("Unable to parse metadata in %s: %s", name.c_str(), e.what()); LOGE("Unable to parse metadata in %s: %s", name.c_str(), e.what());
delete overriddenFile; delete overriddenFile;
return nullptr; return metadataResultProviderFailed(env);
} }
} }
+20 -15
View File
@@ -34,7 +34,7 @@ import org.oxycblt.musikr.tag.parse.ParsedTags
*/ */
interface Cache { 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]. * several outcomes represented by [CacheResult].
* *
* @param file the [File] to read from the cache * @param file the [File] to read from the cache
@@ -53,32 +53,42 @@ interface Cache {
*/ */
interface MutableCache : 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 * This should commit the metadata to the repository in such a way that it can be retrieved
* later by [read] using only the [File]. * 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. * list.
* *
* This is paramount for any long-term persistence to maintain correct Date added metadata and * This is paramount for any long-term persistence to maintain correct Date added metadata and
* to avoid having space taken up by useless data. * 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. * 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. */ /** 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. */ /** The file this song corresponds to. */
val file: File, 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. */ /** The properties of the song. */
val properties: Properties, val properties: Properties,
/** The parsed tags of the song. */ /** The parsed tags of the song. */
@@ -88,11 +98,6 @@ data class CachedSong(
* implementation used. * implementation used.
*/ */
val coverId: String?, 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. */ /** A result of a cache lookup. */
@@ -100,9 +105,9 @@ sealed interface CacheResult {
/** /**
* A cache entry was found. * 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. * 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.correctWhitespace
import org.oxycblt.musikr.util.splitEscaped 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() { internal abstract class CacheDatabase : RoomDatabase() {
abstract fun readDao(): CacheReadDao abstract fun readDao(): CacheReadDao
@@ -56,12 +56,12 @@ internal abstract class CacheDatabase : RoomDatabase() {
@Dao @Dao
internal interface CacheReadDao { internal interface CacheReadDao {
@Query("SELECT * FROM CachedSongData") suspend fun selectAllSongs(): List<CachedSongData> @Query("SELECT * FROM CachedFileData") suspend fun selectAllSongs(): List<CachedFileData>
} }
@Dao @Dao
internal interface CacheWriteDao { internal interface CacheWriteDao {
@Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun updateSong(data: CachedSongData) @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun updateSong(data: CachedFileData)
@Transaction @Transaction
suspend fun deleteExcludingUris(uris: Set<String>) { 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>) suspend fun deleteExcludingUriChunk(uris: List<String>)
} }
@Entity @Entity
@TypeConverters(CachedSongData.Converters::class) @TypeConverters(CachedFileData.Converters::class)
internal data class CachedSongData( internal data class CachedFileData(
@PrimaryKey val uri: Uri, @PrimaryKey val uri: Uri,
val modifiedMs: Long, val modifiedMs: Long,
val addedMs: Long, val addedMs: Long,
val mimeType: String, val mimeType: String?,
val durationMs: Long, val durationMs: Long?,
val bitrateKbps: Int, val bitrateKbps: Int?,
val sampleRateHz: Int, val sampleRateHz: Int?,
val musicBrainzId: String?, val musicBrainzId: String?,
val name: String?, val name: String?,
val sortName: String?, val sortName: String?,
@@ -97,14 +97,14 @@ internal data class CachedSongData(
val albumMusicBrainzId: String?, val albumMusicBrainzId: String?,
val albumName: String?, val albumName: String?,
val albumSortName: String?, val albumSortName: String?,
val releaseTypes: List<String>, val releaseTypes: List<String>?,
val artistMusicBrainzIds: List<String>, val artistMusicBrainzIds: List<String>?,
val artistNames: List<String>, val artistNames: List<String>?,
val artistSortNames: List<String>, val artistSortNames: List<String>?,
val albumArtistMusicBrainzIds: List<String>, val albumArtistMusicBrainzIds: List<String>?,
val albumArtistNames: List<String>, val albumArtistNames: List<String>?,
val albumArtistSortNames: List<String>, val albumArtistSortNames: List<String>?,
val genreNames: List<String>, val genreNames: List<String>?,
val replayGainTrackAdjustment: Float?, val replayGainTrackAdjustment: Float?,
val replayGainAlbumAdjustment: Float?, val replayGainAlbumAdjustment: Float?,
val coverId: String?, val coverId: String?,
+69 -64
View File
@@ -22,9 +22,10 @@ import android.content.Context
import android.net.Uri import android.net.Uri
import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.sync.withLock
import org.oxycblt.musikr.cache.Audio
import org.oxycblt.musikr.cache.Cache import org.oxycblt.musikr.cache.Cache
import org.oxycblt.musikr.cache.CacheResult 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.cache.MutableCache
import org.oxycblt.musikr.fs.File import org.oxycblt.musikr.fs.File
import org.oxycblt.musikr.metadata.Properties import org.oxycblt.musikr.metadata.Properties
@@ -36,7 +37,7 @@ import org.oxycblt.musikr.tag.parse.ParsedTags
* Create an instance with [from]. * Create an instance with [from].
*/ */
class DBCache private constructor(private val readDao: CacheReadDao) : Cache { 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() private val mappingLock = Mutex()
override suspend fun read(file: File): CacheResult { 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) return CacheResult.Stale(file, dbSong.addedMs)
} }
val song = val song =
CachedSong( CachedFile(
file, file,
Properties( dbSong.mimeType?.let {
dbSong.mimeType, Audio(
dbSong.durationMs, Properties(
dbSong.bitrateKbps, dbSong.mimeType,
dbSong.sampleRateHz, dbSong.durationMs!!,
), dbSong.bitrateKbps!!,
ParsedTags( dbSong.sampleRateHz!!,
musicBrainzId = dbSong.musicBrainzId, ),
name = dbSong.name, ParsedTags(
sortName = dbSong.sortName, musicBrainzId = dbSong.musicBrainzId,
durationMs = dbSong.durationMs, name = dbSong.name,
track = dbSong.track, sortName = dbSong.sortName,
disc = dbSong.disc, durationMs = dbSong.durationMs,
subtitle = dbSong.subtitle, track = dbSong.track,
date = dbSong.date, disc = dbSong.disc,
albumMusicBrainzId = dbSong.albumMusicBrainzId, subtitle = dbSong.subtitle,
albumName = dbSong.albumName, date = dbSong.date,
albumSortName = dbSong.albumSortName, albumMusicBrainzId = dbSong.albumMusicBrainzId,
releaseTypes = dbSong.releaseTypes, albumName = dbSong.albumName,
artistMusicBrainzIds = dbSong.artistMusicBrainzIds, albumSortName = dbSong.albumSortName,
artistNames = dbSong.artistNames, releaseTypes = dbSong.releaseTypes!!,
artistSortNames = dbSong.artistSortNames, artistMusicBrainzIds = dbSong.artistMusicBrainzIds!!,
albumArtistMusicBrainzIds = dbSong.albumArtistMusicBrainzIds, artistNames = dbSong.artistNames!!,
albumArtistNames = dbSong.albumArtistNames, artistSortNames = dbSong.artistSortNames!!,
albumArtistSortNames = dbSong.albumArtistSortNames, albumArtistMusicBrainzIds = dbSong.albumArtistMusicBrainzIds!!,
genreNames = dbSong.genreNames, albumArtistNames = dbSong.albumArtistNames!!,
replayGainTrackAdjustment = dbSong.replayGainTrackAdjustment, albumArtistSortNames = dbSong.albumArtistSortNames!!,
replayGainAlbumAdjustment = dbSong.replayGainAlbumAdjustment, genreNames = dbSong.genreNames!!,
), replayGainTrackAdjustment = dbSong.replayGainTrackAdjustment,
coverId = dbSong.coverId, replayGainAlbumAdjustment = dbSong.replayGainAlbumAdjustment,
),
coverId = dbSong.coverId,
)
},
addedMs = dbSong.addedMs, addedMs = dbSong.addedMs,
) )
return CacheResult.Hit(song) return CacheResult.Hit(song)
@@ -112,42 +117,42 @@ private constructor(private val inner: DBCache, private val writeDao: CacheWrite
MutableCache { MutableCache {
override suspend fun read(file: File) = inner.read(file) override suspend fun read(file: File) = inner.read(file)
override suspend fun write(cachedSong: CachedSong) { override suspend fun write(cachedFile: CachedFile) {
val dbSong = val dbSong =
CachedSongData( CachedFileData(
uri = cachedSong.file.uri, uri = cachedFile.file.uri,
modifiedMs = cachedSong.file.modifiedMs, modifiedMs = cachedFile.file.modifiedMs,
addedMs = cachedSong.addedMs, addedMs = cachedFile.addedMs,
mimeType = cachedSong.properties.mimeType, mimeType = cachedFile.audio?.properties?.mimeType,
durationMs = cachedSong.properties.durationMs, durationMs = cachedFile.audio?.properties?.durationMs,
bitrateKbps = cachedSong.properties.bitrateKbps, bitrateKbps = cachedFile.audio?.properties?.bitrateKbps,
sampleRateHz = cachedSong.properties.sampleRateHz, sampleRateHz = cachedFile.audio?.properties?.sampleRateHz,
musicBrainzId = cachedSong.tags.musicBrainzId, musicBrainzId = cachedFile.audio?.tags?.musicBrainzId,
name = cachedSong.tags.name, name = cachedFile.audio?.tags?.name,
sortName = cachedSong.tags.sortName, sortName = cachedFile.audio?.tags?.sortName,
track = cachedSong.tags.track, track = cachedFile.audio?.tags?.track,
disc = cachedSong.tags.disc, disc = cachedFile.audio?.tags?.disc,
subtitle = cachedSong.tags.subtitle, subtitle = cachedFile.audio?.tags?.subtitle,
date = cachedSong.tags.date, date = cachedFile.audio?.tags?.date,
albumMusicBrainzId = cachedSong.tags.albumMusicBrainzId, albumMusicBrainzId = cachedFile.audio?.tags?.albumMusicBrainzId,
albumName = cachedSong.tags.albumName, albumName = cachedFile.audio?.tags?.albumName,
albumSortName = cachedSong.tags.albumSortName, albumSortName = cachedFile.audio?.tags?.albumSortName,
releaseTypes = cachedSong.tags.releaseTypes, releaseTypes = cachedFile.audio?.tags?.releaseTypes,
artistMusicBrainzIds = cachedSong.tags.artistMusicBrainzIds, artistMusicBrainzIds = cachedFile.audio?.tags?.artistMusicBrainzIds,
artistNames = cachedSong.tags.artistNames, artistNames = cachedFile.audio?.tags?.artistNames,
artistSortNames = cachedSong.tags.artistSortNames, artistSortNames = cachedFile.audio?.tags?.artistSortNames,
albumArtistMusicBrainzIds = cachedSong.tags.albumArtistMusicBrainzIds, albumArtistMusicBrainzIds = cachedFile.audio?.tags?.albumArtistMusicBrainzIds,
albumArtistNames = cachedSong.tags.albumArtistNames, albumArtistNames = cachedFile.audio?.tags?.albumArtistNames,
albumArtistSortNames = cachedSong.tags.albumArtistSortNames, albumArtistSortNames = cachedFile.audio?.tags?.albumArtistSortNames,
genreNames = cachedSong.tags.genreNames, genreNames = cachedFile.audio?.tags?.genreNames,
replayGainTrackAdjustment = cachedSong.tags.replayGainTrackAdjustment, replayGainTrackAdjustment = cachedFile.audio?.tags?.replayGainTrackAdjustment,
replayGainAlbumAdjustment = cachedSong.tags.replayGainAlbumAdjustment, replayGainAlbumAdjustment = cachedFile.audio?.tags?.replayGainAlbumAdjustment,
coverId = cachedSong.coverId, coverId = cachedFile.audio?.coverId,
) )
writeDao.updateSong(dbSong) 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() }) 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() override val id = PREFIX + uri.toString()
// Implies that client will manage freeing the resources themselves. // 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") @SuppressLint("Recycle")
override suspend fun fd(): ParcelFileDescriptor? = override suspend fun fd(): ParcelFileDescriptor? =
withContext(Dispatchers.IO) { context.contentResolver.openFileDescriptor(uri, "r") } 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 import org.oxycblt.musikr.fs.File
internal interface MetadataExtractor { internal interface MetadataExtractor {
suspend fun extract(deviceFile: File): Metadata? suspend fun extract(deviceFile: File): MetadataResult
companion object { companion object {
fun from(context: Context): MetadataExtractor = 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) : private class MetadataExtractorImpl(private val contentResolver: ContentResolver) :
MetadataExtractor { MetadataExtractor {
override suspend fun extract(deviceFile: File): Metadata? = override suspend fun extract(deviceFile: File): MetadataResult =
withContext(Dispatchers.IO) { withContext(Dispatchers.IO) {
contentResolver.openFileDescriptor(deviceFile.uri, "r")?.use { fd -> contentResolver.openFileDescriptor(deviceFile.uri, "r")?.use { fd ->
val fis = FileInputStream(fd.fileDescriptor) val fis = FileInputStream(fd.fileDescriptor)
TagLibJNI.open(deviceFile, fis).also { fis.close() } 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. * 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 inputStream = NativeInputStream(deviceFile, fis)
val tag = openNative(inputStream) val tag = openNative(inputStream)
inputStream.close() inputStream.close()
return tag 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) { when (extracted) {
is RawSong -> builder.add(tagInterpreter.interpret(extracted)) is RawSong -> builder.add(tagInterpreter.interpret(extracted))
is RawPlaylist -> builder.add(playlistInterpreter.interpret(extracted.file)) is RawPlaylist -> builder.add(playlistInterpreter.interpret(extracted.file))
is NotAudio -> {}
is InvalidSong -> {} is InvalidSong -> {}
} }
builder
} }
val graph = builder.build() val graph = builder.build()
@@ -26,12 +26,10 @@ import kotlinx.coroutines.channels.Channel
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
import org.oxycblt.musikr.cache.CachedSong import org.oxycblt.musikr.cache.CachedFile
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.fs.File
import org.oxycblt.musikr.playlist.m3u.M3U
import org.oxycblt.musikr.util.mapParallel import org.oxycblt.musikr.util.mapParallel
import org.oxycblt.musikr.util.merge import org.oxycblt.musikr.util.merge
import org.oxycblt.musikr.util.tryAsyncWith 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 classified = Channel<Classified>(Channel.UNLIMITED)
val classifiedTask = val classifiedTask =
scope.mapParallel(PARALLELISM, files, classified, Dispatchers.IO) { file -> scope.mapParallel(PARALLELISM, files, classified, Dispatchers.IO) { file ->
if (!file.mimeType.startsWith("audio/") && file.mimeType != M3U.MIME_TYPE) { when (val cacheResult = storage.cache.read(file)) {
return@mapParallel null is CacheResult.Hit -> NeedsHydration(cacheResult.file)
}
val cacheResult = storage.cache.read(file)
when (cacheResult) {
is CacheResult.Hit -> NeedsCover(cacheResult.song)
is CacheResult.Stale -> Finalized(NewSong(cacheResult.file)) is CacheResult.Stale -> Finalized(NewSong(cacheResult.file))
is CacheResult.Miss -> 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 -> scope.mapParallel(PARALLELISM, classified, finalized, Dispatchers.IO) { item ->
when (item) { when (item) {
is Finalized -> item is Finalized -> item
is NeedsCover -> { is NeedsHydration -> {
when ( val audio = item.cachedFile.audio ?: return@mapParallel Finalized(NotAudio)
val coverResult = val coverId =
item.cachedSong.coverId?.let { id -> storage.covers.obtain(id) } when (
) { val result = audio.coverId?.let { id -> storage.covers.obtain(id) }
is CoverResult.Hit -> ) {
Finalized(item.cachedSong.toRawSong(coverResult.cover)) is CoverResult.Hit -> result.cover
null -> Finalized(item.cachedSong.toRawSong(null)) is CoverResult.Miss ->
else -> Finalized(NewSong(item.cachedSong.file)) 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 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 data class Finalized(val explored: Explored) : Classified
private fun CachedSong.toRawSong(cover: Cover?) =
RawSong(file, properties, tags, cover, addedMs)
private companion object { private companion object {
const val PARALLELISM = 8 const val PARALLELISM = 8
} }
@@ -24,13 +24,15 @@ import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.Channel
import org.oxycblt.musikr.Config 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.cache.MutableCache
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.covers.MutableCovers 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.metadata.MetadataResult
import org.oxycblt.musikr.tag.parse.TagParser import org.oxycblt.musikr.tag.parse.TagParser
import org.oxycblt.musikr.util.mapParallel import org.oxycblt.musikr.util.mapParallel
import org.oxycblt.musikr.util.merge import org.oxycblt.musikr.util.merge
@@ -73,10 +75,16 @@ private class ExtractStepImpl(
is RawSong -> Finalized(item) is RawSong -> Finalized(item)
is RawPlaylist -> Finalized(item) is RawPlaylist -> Finalized(item)
is NewSong -> { is NewSong -> {
val metadata = metadataExtractor.extract(item.file) when (val result = metadataExtractor.extract(item.file)) {
if (metadata != null) NeedsParsing(item, metadata) is MetadataResult.Success ->
else Finalized(InvalidSong) 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) val parsed = Channel<ParsedCachingItem>(Channel.UNLIMITED)
@@ -113,18 +121,18 @@ private class ExtractStepImpl(
} }
val finalizedTask = val finalizedTask =
scope.tryAsyncWith(extracted, Dispatchers.IO) { scope.tryAsyncWith(extracted, Dispatchers.IO) {
val exclude = mutableListOf<CachedSong>() val exclude = mutableListOf<CachedFile>()
for (item in parsed) { for (item in parsed) {
val result = val result =
when (item) { when (item) {
is Finalized -> item is Finalized -> item
is NeedsCaching -> { is NeedsCaching -> {
cache.write(item.rawSong.toCachedSong()) cache.write(item.rawSong.toCachedFile())
Finalized(item.rawSong) Finalized(item.rawSong)
} }
} }
if (result.extracted is RawSong) { if (result.extracted is RawSong) {
exclude.add(result.extracted.toCachedSong()) exclude.add(result.extracted.toCachedFile())
} }
it.send(result.extracted) it.send(result.extracted)
} }
@@ -145,7 +153,8 @@ private class ExtractStepImpl(
private data class Finalized(val extracted: Extracted) : ParsedExtractItem, ParsedCachingItem 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 { private companion object {
const val PARALLELISM = 8 const val PARALLELISM = 8
@@ -46,6 +46,8 @@ internal sealed interface Extracted : PipelineItem {
internal data object InvalidSong : Extracted.Invalid 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 RawPlaylist(val file: PlaylistFile) : Explored.Known, Extracted.Valid
internal data class RawSong( internal data class RawSong(
@@ -79,7 +79,7 @@ fun <T, R> CoroutineScope.mapParallel(
input: Channel<T>, input: Channel<T>,
output: Channel<R>, output: Channel<R>,
context: CoroutineContext = Dispatchers.Default, context: CoroutineContext = Dispatchers.Default,
block: suspend (T) -> R?, block: suspend (T) -> R,
): Deferred<Result<Unit>> { ): Deferred<Result<Unit>> {
return tryAsync(context) { return tryAsync(context) {
val deferreds = ArrayList<Deferred<Result<Unit>>>() val deferreds = ArrayList<Deferred<Result<Unit>>>()
@@ -87,14 +87,13 @@ fun <T, R> CoroutineScope.mapParallel(
val deferred = val deferred =
tryAsync(context) { tryAsync(context) {
for (item in input) { for (item in input) {
block(item)?.let { output.send(it) } block(item).let { output.send(it) }
} }
} }
deferreds.add(deferred) deferreds.add(deferred)
} }
deferreds.tryAwaitAll() deferreds.tryAwaitAll()
output.close() output.close()
Unit
} }
} }