Author SHA1 Message Date
jay e12f00c49b chore: release v4.1.5-fork.4
Build / build (push) Successful in 6m19s
Release / release (push) Successful in 6m49s
2026-11-12 19:31:58 -05:00
jay 66947b80bc musikr: parse APE tags on mpeg files, log ReplayGain values in debug 2026-11-12 19:27:33 -05:00
jay 208e48a97b musikr: read ReplayGain with APE preferred over ID3v2 2026-11-12 19:24:56 -05:00
jay 65bfdf6b7d musikr: import and track discovered playlists during indexing 2026-11-12 18:54:33 -05:00
jay f492410484 musikr: never reconcile destructively 2026-11-12 18:48:03 -05:00
jay 39deae7644 musikr: buffer discovered playlist files during exploration 2026-11-12 18:40:40 -05:00
jay 38bd9cd260 musikr: track playlist source files in the database 2026-11-12 18:26:13 -05:00
jay ecd71d2699 musikr: create tracked playlists for newly discovered files 2026-11-12 18:22:22 -05:00
jay 366945499e musikr: reconcile tracked playlists against discovered files 2026-11-12 18:20:54 -05:00
jay 843bf55fd1 musikr: pin playlist-name parsing 2026-11-12 18:18:25 -05:00
jay e4cca068db musikr: resolve playlist imports by probe-and-lock 2026-11-12 18:17:03 -05:00
jay a9f6c82041 musikr: pin null when no playlist entry resolves 2026-11-12 18:05:43 -05:00
jay e4d4da371d musikr: pin probe advancement past a missing first entry 2026-11-12 18:04:02 -05:00
jay ac0966c8ea musikr: pin survivor resolution when playlist entries are missing 2026-11-12 18:02:25 -05:00
jay 960061e615 musikr: strip leading segments when probing absolute playlist entries 2026-11-12 18:01:38 -05:00
jay 3387ccedaf musikr: pin root order as precedence in playlist resolution 2026-11-12 18:00:15 -05:00
jay 18fde00a41 musikr: pin dotdot resolution of playlist entries 2026-11-12 17:58:58 -05:00
jay e206acde3f musikr: normalize dot segments when resolving playlist entries 2026-11-12 17:57:37 -05:00
jay 7ad4fe5f8c musikr: resolve playlist entries by probe-and-lock against candidate roots 2026-11-12 17:56:13 -05:00
31 changed files with 1018 additions and 150 deletions
+2 -2
View File
@@ -16,8 +16,8 @@ android {
defaultConfig { defaultConfig {
applicationId namespace applicationId namespace
versionName "4.1.5-fork.3" versionName "4.1.5-fork.4"
versionCode 78 versionCode 79
minSdk min_sdk minSdk min_sdk
// randomly flickers between deprecated and required depending on what mood my gradle is in // randomly flickers between deprecated and required depending on what mood my gradle is in
@@ -23,6 +23,7 @@ import dagger.hilt.android.qualifiers.ApplicationContext
import java.util.UUID import java.util.UUID
import javax.inject.Inject import javax.inject.Inject
import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CancellationException
import org.oxycblt.auxio.BuildConfig
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job import kotlinx.coroutines.Job
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
@@ -411,6 +412,15 @@ constructor(
val start = System.currentTimeMillis() val start = System.currentTimeMillis()
val result = Musikr.new(context, config).run(::emitIndexingProgress) val result = Musikr.new(context, config).run(::emitIndexingProgress)
L.d("Index finished in ${System.currentTimeMillis() - start}ms") L.d("Index finished in ${System.currentTimeMillis() - start}ms")
if (BuildConfig.DEBUG) {
// Surface parsed ReplayGain values for logcat verification.
for (song in result.library.songs) {
val rg = song.replayGainAdjustment
if (rg.track != null || rg.album != null) {
L.d("RG: ${song.name.raw} track=${rg.track} album=${rg.album}")
}
}
}
// Music loading completed, update the revision right now so we re-use this work // Music loading completed, update the revision right now so we re-use this work
// later. // later.
L.d("Revisioning from $currentRevision -> $newRevision") L.d("Revisioning from $currentRevision -> $newRevision")
@@ -53,6 +53,7 @@ class MusicViewModel
constructor( constructor(
@ApplicationContext context: Context, @ApplicationContext context: Context,
private val listSettings: ListSettings, private val listSettings: ListSettings,
private val musicSettings: MusicSettings,
private val musicRepository: MusicRepository, private val musicRepository: MusicRepository,
) : ViewModel(), MusicRepository.UpdateListener, MusicRepository.IndexingListener { ) : ViewModel(), MusicRepository.UpdateListener, MusicRepository.IndexingListener {
private val externalPlaylistManager = ExternalPlaylistManager.from(context) private val externalPlaylistManager = ExternalPlaylistManager.from(context)
@@ -160,24 +161,19 @@ constructor(
fun importPlaylist(uri: Uri? = null, target: Playlist? = null) { fun importPlaylist(uri: Uri? = null, target: Playlist? = null) {
if (uri != null) { if (uri != null) {
viewModelScope.launch(Dispatchers.IO) { viewModelScope.launch(Dispatchers.IO) {
val importedPlaylist = externalPlaylistManager.import(uri) val library = musicRepository.library ?: return@launch
val importedPlaylist =
externalPlaylistManager.import(
uri,
musicSettings.safQuery.source.map { it.path },
library,
)
if (importedPlaylist == null) { if (importedPlaylist == null) {
L.e("Could not import playlist") L.e("Could not import playlist")
playlistMessage.put(PlaylistMessage.ImportFailed) playlistMessage.put(PlaylistMessage.ImportFailed)
return@launch return@launch
} }
val songs = importedPlaylist.songs
val library = musicRepository.library ?: return@launch
val songs =
importedPlaylist.paths.mapNotNull {
it.firstNotNullOfOrNull(library::findSongByPath)
}
if (songs.isEmpty()) {
L.e("No songs found")
playlistMessage.put(PlaylistMessage.ImportFailed)
return@launch
}
if (target !== null) { if (target !== null) {
if (importedPlaylist.name != null && importedPlaylist.name != target.name.raw) { if (importedPlaylist.name != null && importedPlaylist.name != target.name.raw) {
+11 -3
View File
@@ -32,7 +32,7 @@
#include "JByteArrayRef.h" #include "JByteArrayRef.h"
JMetadataBuilder::JMetadataBuilder(JNIEnv *env) : env(env), id3v2(env), xiph( JMetadataBuilder::JMetadataBuilder(JNIEnv *env) : env(env), id3v2(env), xiph(
env), mp4(env), cover(), properties(nullptr) { env), mp4(env), ape(env), cover(), properties(nullptr) {
} }
void JMetadataBuilder::setMimeType(TagLib::String type) { void JMetadataBuilder::setMimeType(TagLib::String type) {
@@ -94,6 +94,13 @@ void JMetadataBuilder::setId3v2(TagLib::ID3v2::Tag &tag) {
} }
} }
void JMetadataBuilder::setApe(TagLib::APE::Tag &tag) {
for (auto item : tag.itemListMap()) {
auto key = item.first.upper();
ape.add_custom(key, item.second.values());
}
}
void JMetadataBuilder::setXiph(TagLib::Ogg::XiphComment &tag) { void JMetadataBuilder::setXiph(TagLib::Ogg::XiphComment &tag) {
for (auto field : tag.fieldListMap()) { for (auto field : tag.fieldListMap()) {
auto key = field.first.upper(); auto key = field.first.upper();
@@ -203,15 +210,16 @@ jobject JMetadataBuilder::build() {
JClassRef jMetadataClass { env, "org/oxycblt/musikr/metadata/Metadata" }; JClassRef jMetadataClass { env, "org/oxycblt/musikr/metadata/Metadata" };
jmethodID jMetadataInitMethod = jMetadataClass.method("<init>", jmethodID jMetadataInitMethod = jMetadataClass.method("<init>",
"(Ljava/util/Map;Ljava/util/Map;Ljava/util/Map;[BLorg/" "(Ljava/util/Map;Ljava/util/Map;Ljava/util/Map;Ljava/util/Map;[BLorg/"
"oxycblt/musikr/metadata/Properties;)V"); "oxycblt/musikr/metadata/Properties;)V");
auto jId3v2Map = id3v2.getObject(); auto jId3v2Map = id3v2.getObject();
auto jXiphMap = xiph.getObject(); auto jXiphMap = xiph.getObject();
auto jMp4Map = mp4.getObject(); auto jMp4Map = mp4.getObject();
auto jApeMap = ape.getObject();
if (cover.has_value()) { if (cover.has_value()) {
JByteArrayRef jCoverArray { env, cover.value() }; JByteArrayRef jCoverArray { env, cover.value() };
jobject result = env->NewObject(*jMetadataClass, jMetadataInitMethod, jobject result = env->NewObject(*jMetadataClass, jMetadataInitMethod,
**jId3v2Map, **jXiphMap, **jMp4Map, *jCoverArray, *jProperties); **jId3v2Map, **jXiphMap, **jMp4Map, **jApeMap, *jCoverArray, *jProperties);
return result; return result;
} }
return env->NewObject(*jMetadataClass, jMetadataInitMethod, **jId3v2Map, return env->NewObject(*jMetadataClass, jMetadataInitMethod, **jId3v2Map,
+3
View File
@@ -27,6 +27,7 @@
#include "taglib/id3v2tag.h" #include "taglib/id3v2tag.h"
#include "taglib/xiphcomment.h" #include "taglib/xiphcomment.h"
#include "taglib/mp4tag.h" #include "taglib/mp4tag.h"
#include "taglib/apetag.h"
#include "taglib/audioproperties.h" #include "taglib/audioproperties.h"
#include "JTagMap.h" #include "JTagMap.h"
@@ -40,6 +41,7 @@ public:
void setId3v2(TagLib::ID3v2::Tag &tag); void setId3v2(TagLib::ID3v2::Tag &tag);
void setXiph(TagLib::Ogg::XiphComment &tag); void setXiph(TagLib::Ogg::XiphComment &tag);
void setMp4(TagLib::MP4::Tag &tag); void setMp4(TagLib::MP4::Tag &tag);
void setApe(TagLib::APE::Tag &tag);
void setFlacPictures(TagLib::List<TagLib::FLAC::Picture*> &pics); void setFlacPictures(TagLib::List<TagLib::FLAC::Picture*> &pics);
void setProperties(TagLib::AudioProperties *properties); void setProperties(TagLib::AudioProperties *properties);
@@ -56,6 +58,7 @@ private:
JTagMap id3v2; JTagMap id3v2;
JTagMap xiph; JTagMap xiph;
JTagMap mp4; JTagMap mp4;
JTagMap ape;
}; };
#endif //AUXIO_JMETADATABUILDER_H #endif //AUXIO_JMETADATABUILDER_H
+1 -1
View File
@@ -28,7 +28,7 @@ build_for_arch() {
cmake -B $DST_DIR -DANDROID_NDK_PATH=${NDK_PATH} -DCMAKE_TOOLCHAIN_FILE=${NDK_TOOLCHAIN} \ cmake -B $DST_DIR -DANDROID_NDK_PATH=${NDK_PATH} -DCMAKE_TOOLCHAIN_FILE=${NDK_TOOLCHAIN} \
-DANDROID_ABI=$ARCH -DBUILD_SHARED_LIBS=OFF -DVISIBILITY_HIDDEN=ON -DBUILD_TESTING=OFF \ -DANDROID_ABI=$ARCH -DBUILD_SHARED_LIBS=OFF -DVISIBILITY_HIDDEN=ON -DBUILD_TESTING=OFF \
-DBUILD_EXAMPLES=OFF -DBUILD_BINDINGS=OFF -DWITH_ZLIB=OFF -DCMAKE_BUILD_TYPE=Release \ -DBUILD_EXAMPLES=OFF -DBUILD_BINDINGS=OFF -DWITH_ZLIB=OFF -DCMAKE_BUILD_TYPE=Release \
-DWITH_APE=OFF -DWITH_ASF=OFF -DWITH_ASF=OFF -DWITH_MOD=OFF -DWITH_SHORTEN=OFF \ -DWITH_APE=ON -DWITH_ASF=OFF -DWITH_ASF=OFF -DWITH_MOD=OFF -DWITH_SHORTEN=OFF \
-DWITH_TRUEAUDIO=OFF -DCMAKE_CXX_FLAGS="-fPIC" -DWITH_TRUEAUDIO=OFF -DCMAKE_CXX_FLAGS="-fPIC"
# Try to parallelize the build # Try to parallelize the build
cmake --build $DST_DIR --config Release -j$(nproc) cmake --build $DST_DIR --config Release -j$(nproc)
+8
View File
@@ -51,6 +51,14 @@ bool parseMpeg(const std::string &name, TagLib::MPEG::File *mpegFile,
LOGE("Unable to parse ID3v2 tag in %s: %s", name.c_str(), e.what()); LOGE("Unable to parse ID3v2 tag in %s: %s", name.c_str(), e.what());
} }
} }
auto apeTag = mpegFile->APETag();
if (apeTag != nullptr) {
try {
jBuilder.setApe(*apeTag);
} catch (std::exception &e) {
LOGE("Unable to parse APE tag in %s: %s", name.c_str(), e.what());
}
}
return true; return true;
} }
@@ -19,9 +19,11 @@
package org.oxycblt.musikr package org.oxycblt.musikr
import android.content.Context import android.content.Context
import java.util.Collections
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.coroutineScope
import org.oxycblt.musikr.fs.File
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.Explored
@@ -117,7 +119,8 @@ private class MusikrImpl(
var explored = 0 var explored = 0
var loaded = 0 var loaded = 0
val exploredChannel = Channel<Explored>(Channel.UNLIMITED) val exploredChannel = Channel<Explored>(Channel.UNLIMITED)
val exploredTask = exploreStep.explore(this, exploredChannel) val playlistFiles = Collections.synchronizedList(mutableListOf<File>())
val exploredTask = exploreStep.explore(this, exploredChannel, playlistFiles)
val trackedExploredChannel = Channel<Explored>(Channel.UNLIMITED) val trackedExploredChannel = Channel<Explored>(Channel.UNLIMITED)
val trackedExploredTask = val trackedExploredTask =
tryAsyncWith(trackedExploredChannel, Dispatchers.Main) { tryAsyncWith(trackedExploredChannel, Dispatchers.Main) {
@@ -139,7 +142,7 @@ private class MusikrImpl(
} }
onProgress(IndexingProgress.Indeterminate) onProgress(IndexingProgress.Indeterminate)
} }
val library = evaluateStep.evaluate(trackedExtractedChannel) val library = evaluateStep.evaluate(trackedExtractedChannel, playlistFiles)
merge(exploredTask, extractedTask, trackedExploredTask, trackedExtractedTask).await() merge(exploredTask, extractedTask, trackedExploredTask, trackedExtractedTask).await()
LibraryResultImpl(config, library) LibraryResultImpl(config, library)
} }
@@ -24,6 +24,9 @@ import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
interface FS { interface FS {
/** The roots playlist entries resolve against, in precedence order. May be empty. */
val locationRoots: List<Path>
suspend fun explore(files: Channel<File>): Deferred<Result<Unit>> suspend fun explore(files: Channel<File>): Deferred<Result<Unit>>
fun track(): Flow<FSUpdate> fun track(): Flow<FSUpdate>
@@ -35,6 +35,7 @@ import org.oxycblt.musikr.fs.FS
import org.oxycblt.musikr.fs.FSUpdate import org.oxycblt.musikr.fs.FSUpdate
import org.oxycblt.musikr.fs.File 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.MediaStorePathInterpreter import org.oxycblt.musikr.fs.path.MediaStorePathInterpreter
import org.oxycblt.musikr.fs.path.VolumeManager import org.oxycblt.musikr.fs.path.VolumeManager
import org.oxycblt.musikr.fs.saf.contentResolverSafe import org.oxycblt.musikr.fs.saf.contentResolverSafe
@@ -54,6 +55,15 @@ private constructor(
) : FS { ) : FS {
private val pathInterpreterFactory = MediaStorePathInterpreter.Factory.from(volumeManager) private val pathInterpreterFactory = MediaStorePathInterpreter.Factory.from(volumeManager)
// Include-mode filters are the closest thing MediaStore has to configured locations.
override val locationRoots: List<Path>
get() =
if (query.mode == FilterMode.INCLUDE) {
query.filtered.map { it.path }
} else {
emptyList()
}
@OptIn(ExperimentalCoroutinesApi::class) @OptIn(ExperimentalCoroutinesApi::class)
override suspend fun explore(files: Channel<File>): Deferred<Result<Unit>> = coroutineScope { override suspend fun explore(files: Channel<File>): Deferred<Result<Unit>> = coroutineScope {
tryAsyncWith(files, Dispatchers.IO) { channel -> tryAsyncWith(files, Dispatchers.IO) { channel ->
@@ -54,6 +54,9 @@ private constructor(
private val contentResolver: ContentResolver, private val contentResolver: ContentResolver,
private val query: Query, private val query: Query,
) : FS { ) : FS {
override val locationRoots: List<Path>
get() = query.source.map { it.path }
override suspend fun explore(files: Channel<File>): Deferred<Result<Unit>> = coroutineScope { override suspend fun explore(files: Channel<File>): Deferred<Result<Unit>> = coroutineScope {
tryAsyncWith(files, Dispatchers.Main) { tryAsyncWith(files, Dispatchers.Main) {
query.source query.source
@@ -22,6 +22,7 @@ data class Metadata(
val id3v2: Map<String, List<String>>, val id3v2: Map<String, List<String>>,
val xiph: Map<String, List<String>>, val xiph: Map<String, List<String>>,
val mp4: Map<String, List<String>>, val mp4: Map<String, List<String>>,
val ape: Map<String, List<String>>,
val cover: ByteArray?, val cover: ByteArray?,
val properties: Properties, val properties: Properties,
) { ) {
@@ -34,6 +35,7 @@ data class Metadata(
if (id3v2 != other.id3v2) return false if (id3v2 != other.id3v2) return false
if (xiph != other.xiph) return false if (xiph != other.xiph) return false
if (mp4 != other.mp4) return false if (mp4 != other.mp4) return false
if (ape != other.ape) return false
if (cover != null) { if (cover != null) {
if (other.cover == null) return false if (other.cover == null) return false
if (!cover.contentEquals(other.cover)) return false if (!cover.contentEquals(other.cover)) return false
@@ -47,6 +49,7 @@ data class Metadata(
var result = id3v2.hashCode() var result = id3v2.hashCode()
result = 31 * result + xiph.hashCode() result = 31 * result + xiph.hashCode()
result = 31 * result + mp4.hashCode() result = 31 * result + mp4.hashCode()
result = 31 * result + ape.hashCode()
result = 31 * result + (cover?.contentHashCode() ?: 0) result = 31 * result + (cover?.contentHashCode() ?: 0)
result = 31 * result + properties.hashCode() result = 31 * result + properties.hashCode()
return result return result
@@ -19,24 +19,39 @@
package org.oxycblt.musikr.pipeline package org.oxycblt.musikr.pipeline
import android.content.Context import android.content.Context
import java.util.zip.CRC32
import java.util.zip.CheckedInputStream
import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.Channel
import org.oxycblt.musikr.BuildConfig import org.oxycblt.musikr.BuildConfig
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
import org.oxycblt.musikr.fs.FS
import org.oxycblt.musikr.fs.File
import org.oxycblt.musikr.fs.saf.contentResolverSafe
import org.oxycblt.musikr.graph.MusicGraph import org.oxycblt.musikr.graph.MusicGraph
import org.oxycblt.musikr.model.LibraryFactory import org.oxycblt.musikr.model.LibraryFactory
import org.oxycblt.musikr.playlist.PlaylistPathResolver
import org.oxycblt.musikr.playlist.PlaylistReconciler
import org.oxycblt.musikr.playlist.db.StoredPlaylists import org.oxycblt.musikr.playlist.db.StoredPlaylists
import org.oxycblt.musikr.playlist.interpret.PlaylistInterpreter import org.oxycblt.musikr.playlist.interpret.PlaylistInterpreter
import org.oxycblt.musikr.playlist.m3u.M3U
import org.oxycblt.musikr.playlist.m3u.ParsedM3U
import org.oxycblt.musikr.playlist.playlistNameFromFileName
import org.oxycblt.musikr.tag.interpret.PreSong
import org.oxycblt.musikr.tag.interpret.TagInterpreter import org.oxycblt.musikr.tag.interpret.TagInterpreter
internal interface EvaluateStep { internal interface EvaluateStep {
suspend fun evaluate(extractedMusic: Channel<Extracted>): MutableLibrary suspend fun evaluate(
extractedMusic: Channel<Extracted>,
playlistFiles: List<File>,
): MutableLibrary
companion object { companion object {
fun new(context: Context, config: Config, interpretation: Interpretation): EvaluateStep = fun new(context: Context, config: Config, interpretation: Interpretation): EvaluateStep =
EvaluateStepImpl( EvaluateStepImpl(
context, context,
config.fs,
TagInterpreter.new(interpretation), TagInterpreter.new(interpretation),
PlaylistInterpreter.new(interpretation), PlaylistInterpreter.new(interpretation),
config.storage.storedPlaylists, config.storage.storedPlaylists,
@@ -47,21 +62,37 @@ internal interface EvaluateStep {
private class EvaluateStepImpl( private class EvaluateStepImpl(
private val context: Context, private val context: Context,
private val fs: FS,
private val tagInterpreter: TagInterpreter, private val tagInterpreter: TagInterpreter,
private val playlistInterpreter: PlaylistInterpreter, private val playlistInterpreter: PlaylistInterpreter,
private val storedPlaylists: StoredPlaylists, private val storedPlaylists: StoredPlaylists,
private val libraryFactory: LibraryFactory, private val libraryFactory: LibraryFactory,
) : EvaluateStep { ) : EvaluateStep {
override suspend fun evaluate(extractedMusic: Channel<Extracted>): MutableLibrary { override suspend fun evaluate(
extractedMusic: Channel<Extracted>,
playlistFiles: List<File>,
): MutableLibrary {
val builder = MusicGraph.builder() val builder = MusicGraph.builder()
val preSongs = mutableListOf<PreSong>()
for (extracted in extractedMusic) { for (extracted in extractedMusic) {
when (extracted) { when (extracted) {
is RawSong -> builder.add(tagInterpreter.interpret(extracted)) is RawSong -> {
is RawPlaylist -> builder.add(playlistInterpreter.interpret(extracted.file)) val preSong = tagInterpreter.interpret(extracted)
preSongs.add(preSong)
builder.add(preSong)
}
is NotAudio -> {} is NotAudio -> {}
is InvalidSong -> {} is InvalidSong -> {}
} }
} }
if (playlistFiles.isNotEmpty()) {
reconcilePlaylists(playlistFiles, preSongs)
}
// Stored playlists enter the graph after the reconcile pass, so the graph sees the
// settled state.
for (playlistFile in storedPlaylists.read()) {
builder.add(playlistInterpreter.interpret(playlistFile))
}
val graph = builder.build() val graph = builder.build()
// Render graph to Graphviz in debug mode // Render graph to Graphviz in debug mode
@@ -72,4 +103,77 @@ private class EvaluateStepImpl(
return libraryFactory.create(graph, storedPlaylists, playlistInterpreter) return libraryFactory.create(graph, storedPlaylists, playlistInterpreter)
} }
/**
* Reconcile the discovered playlist files against the tracked store. Each file is parsed,
* signed, and resolved in one pass; the reconciler decides keep/replace/create, and the
* actions are applied to the store before stored playlists feed the graph.
*/
private suspend fun reconcilePlaylists(playlistFiles: List<File>, preSongs: List<PreSong>) {
val resolver = PlaylistPathResolver()
val m3u = M3U.new()
val uidsByPath = preSongs.associate { it.path to it.v363Uid }
val roots = fs.locationRoots
val discoveredFiles = mutableListOf<DiscoveredFile>()
for (file in playlistFiles) {
val crc = CRC32()
val parsed =
context.contentResolverSafe.openInputStream(file.uri)?.use { stream ->
m3u.read(CheckedInputStream(stream, crc))
}
?: continue
val paths =
resolver.resolve(parsed.entries, listOf(file.path.directory) + roots) { path ->
path in uidsByPath
}
discoveredFiles.add(DiscoveredFile(file, parsed, crc.value, paths ?: emptyList()))
}
val actions =
PlaylistReconciler.reconcile(
storedPlaylists.readTracked(),
discoveredFiles.map {
PlaylistReconciler.Discovered(
it.file.uri.toString(),
it.signature,
it.songPaths.size,
)
},
)
for (action in actions) {
when (action) {
is PlaylistReconciler.Action.Keep -> {}
is PlaylistReconciler.Action.Replace -> {
val file =
discoveredFiles.first { it.file.uri.toString() == action.file.uri }
storedPlaylists.replaceTracked(
action.tracked.uid,
file.name(),
file.songPaths.mapNotNull { uidsByPath[it] },
action.file.signature,
)
}
is PlaylistReconciler.Action.Create -> {
val file =
discoveredFiles.first { it.file.uri.toString() == action.file.uri }
storedPlaylists.newTracked(
file.name(),
file.songPaths.mapNotNull { uidsByPath[it] },
file.file.uri.toString(),
action.file.signature,
)
}
}
}
}
private data class DiscoveredFile(
val file: File,
val parsed: ParsedM3U,
val signature: Long,
val songPaths: List<org.oxycblt.musikr.fs.Path>,
) {
/** The playlist's name: the file's #PLAYLIST entry, else derived from the file name. */
fun name() =
parsed.name ?: file.path.name?.let { playlistNameFromFileName(it) } ?: "Playlist"
}
} }
@@ -36,7 +36,16 @@ import org.oxycblt.musikr.util.merge
import org.oxycblt.musikr.util.tryAsyncWith import org.oxycblt.musikr.util.tryAsyncWith
internal interface ExploreStep { internal interface ExploreStep {
suspend fun explore(scope: CoroutineScope, explored: Channel<Explored>): Deferred<Result<Unit>> /**
* Explore the file system for music, streaming the results into [explored]. Discovered
* playlist files are buffered into [playlistFiles] for reconciliation once the library is
* fully extracted.
*/
suspend fun explore(
scope: CoroutineScope,
explored: Channel<Explored>,
playlistFiles: MutableList<File>,
): Deferred<Result<Unit>>
companion object { companion object {
fun from(context: Context, config: Config): ExploreStep = fun from(context: Context, config: Config): ExploreStep =
@@ -48,6 +57,7 @@ private class ExploreStepImpl(private val fs: FS, private val storage: Storage)
override suspend fun explore( override suspend fun explore(
scope: CoroutineScope, scope: CoroutineScope,
explored: Channel<Explored>, explored: Channel<Explored>,
playlistFiles: MutableList<File>,
): Deferred<Result<Unit>> { ): Deferred<Result<Unit>> {
val files = Channel<File>(Channel.UNLIMITED) val files = Channel<File>(Channel.UNLIMITED)
val filesTask = fs.explore(files) val filesTask = fs.explore(files)
@@ -62,6 +72,10 @@ private class ExploreStepImpl(private val fs: FS, private val storage: Storage)
file.mimeType != "application/x-ogg" && file.mimeType != "application/x-ogg" &&
file.mimeType != "application/octet-stream") file.mimeType != "application/octet-stream")
) { ) {
if (file.mimeType == M3U.MIME_TYPE) {
// Not audio, but still wanted: buffer for the reconcile pass.
playlistFiles.add(file)
}
return@mapParallel Finalized(NotAudio) return@mapParallel Finalized(NotAudio)
} }
when (val cacheResult = storage.cache.read(file)) { when (val cacheResult = storage.cache.read(file)) {
@@ -100,26 +114,14 @@ private class ExploreStepImpl(private val fs: FS, private val storage: Storage)
} }
} }
} }
val playlists = Channel<Explored>(Channel.UNLIMITED)
val playlistsTask =
scope.tryAsyncWith(playlists, Dispatchers.IO) {
for (playlist in storage.storedPlaylists.read()) {
val rawPlaylist = RawPlaylist(playlist)
it.send(rawPlaylist)
}
}
val mergeTask = val mergeTask =
scope.tryAsyncWith(explored, Dispatchers.Main) { scope.tryAsyncWith(explored, Dispatchers.Main) {
for (item in finalized) { for (item in finalized) {
it.send(item.explored) it.send(item.explored)
} }
for (playlist in playlists) {
it.send(playlist)
}
} }
return scope.merge(filesTask, classifiedTask, exploredTask, playlistsTask, mergeTask) return scope.merge(filesTask, classifiedTask, exploredTask, mergeTask)
} }
private sealed interface Classified private sealed interface Classified
@@ -73,7 +73,6 @@ private class ExtractStepImpl(
scope.mapParallel(PARALLELISM, explored, extract, Dispatchers.IO) { item -> scope.mapParallel(PARALLELISM, explored, extract, Dispatchers.IO) { item ->
when (item) { when (item) {
is RawSong -> Finalized(item) is RawSong -> Finalized(item)
is RawPlaylist -> Finalized(item)
is NewSong -> { is NewSong -> {
when (val result = metadataExtractor.extract(item.file)) { when (val result = metadataExtractor.extract(item.file)) {
is MetadataResult.Success -> is MetadataResult.Success ->
@@ -21,7 +21,6 @@ package org.oxycblt.musikr.pipeline
import org.oxycblt.musikr.covers.Cover import org.oxycblt.musikr.covers.Cover
import org.oxycblt.musikr.fs.File import org.oxycblt.musikr.fs.File
import org.oxycblt.musikr.metadata.Properties import org.oxycblt.musikr.metadata.Properties
import org.oxycblt.musikr.playlist.PlaylistFile
import org.oxycblt.musikr.tag.parse.ParsedTags import org.oxycblt.musikr.tag.parse.ParsedTags
internal sealed interface PipelineItem internal sealed interface PipelineItem
@@ -48,8 +47,6 @@ internal data object InvalidSong : Extracted.Invalid
internal data object NotAudio : Explored.Known, Extracted.Valid internal data object NotAudio : Explored.Known, Extracted.Valid
internal data class RawPlaylist(val file: PlaylistFile) : Explored.Known, Extracted.Valid
internal data class RawSong( internal data class RawSong(
val file: File, val file: File,
val properties: Properties, val properties: Properties,
@@ -20,7 +20,9 @@ package org.oxycblt.musikr.playlist
import android.content.Context import android.content.Context
import android.net.Uri import android.net.Uri
import org.oxycblt.musikr.Library
import org.oxycblt.musikr.Playlist import org.oxycblt.musikr.Playlist
import org.oxycblt.musikr.Song
import org.oxycblt.musikr.fs.Components import org.oxycblt.musikr.fs.Components
import org.oxycblt.musikr.fs.Path import org.oxycblt.musikr.fs.Path
import org.oxycblt.musikr.fs.Volume import org.oxycblt.musikr.fs.Volume
@@ -37,13 +39,16 @@ import org.oxycblt.musikr.playlist.m3u.M3U
*/ */
interface ExternalPlaylistManager { interface ExternalPlaylistManager {
/** /**
* Import the playli L.d("Unable to extract bit rate field") st file at the given [uri]. * Import the playlist file at the given [uri].
* *
* @param uri The [Uri] of the playlist file to import. * @param uri The [Uri] of the playlist file to import.
* @return An [ImportedPlaylist] containing the paths to the files listed in the playlist file, * @param roots Candidate roots to resolve entries against after the playlist file's own
* or null if the playlist could not be imported. * directory, in precedence order. Usually the configured music locations.
* @param library The [Library] to resolve entries against.
* @return An [ImportedPlaylist] containing the resolved songs, or null if the playlist could
* not be imported or no entry resolved.
*/ */
suspend fun import(uri: Uri): ImportedPlaylist? suspend fun import(uri: Uri, roots: List<Path>, library: Library): ImportedPlaylist?
/** /**
* Export the given [playlist] to the given [uri]. * Export the given [playlist] to the given [uri].
@@ -60,7 +65,7 @@ interface ExternalPlaylistManager {
ExternalPlaylistManagerImpl( ExternalPlaylistManagerImpl(
context, context,
DocumentPathFactory.from(context), DocumentPathFactory.from(context),
M3U.from(context), M3U.new(),
) )
} }
} }
@@ -80,40 +85,39 @@ data class ExportConfig(val absolute: Boolean, val windowsPaths: Boolean)
* A playlist that has been imported. * A playlist that has been imported.
* *
* @property name The name of the playlist. May be null if not provided. * @property name The name of the playlist. May be null if not provided.
* @property paths The paths of the files in the playlist. * @property songs The resolved songs of the playlist, in file order. Entries that did not
* resolve are dropped.
* @see ExternalPlaylistManager * @see ExternalPlaylistManager
* @see M3U * @see M3U
*/ */
data class ImportedPlaylist(val name: String?, val paths: List<PossiblePaths>) data class ImportedPlaylist(val name: String?, val songs: List<Song>)
typealias PossiblePaths = List<Path>
private class ExternalPlaylistManagerImpl( private class ExternalPlaylistManagerImpl(
private val context: Context, private val context: Context,
private val documentPathFactory: DocumentPathFactory, private val documentPathFactory: DocumentPathFactory,
private val m3u: M3U, private val m3u: M3U,
) : ExternalPlaylistManager { ) : ExternalPlaylistManager {
override suspend fun import(uri: Uri): ImportedPlaylist? { private val resolver = PlaylistPathResolver()
override suspend fun import(uri: Uri, roots: List<Path>, library: Library): ImportedPlaylist? {
val filePath = val filePath =
documentPathFactory.unpackDocumentUri(uri) documentPathFactory.unpackDocumentUri(uri)
?: Path(Volume.ThirdParty(uri), Components.root()) ?: Path(Volume.ThirdParty(uri), Components.root())
return try { return try {
context.contentResolverSafe.openInputStream(uri)?.use { context.contentResolverSafe.openInputStream(uri)?.use {
val imported = m3u.read(it, filePath.directory) ?: return null val parsed = m3u.read(it) ?: return null
val name = imported.name val paths =
if (name != null) { resolver.resolve(parsed.entries, listOf(filePath.directory) + roots) { path ->
return imported library.findSongByPath(path) != null
} }
// Strip extension ?: return null
val fileName = filePath.name ?: return imported val songs = paths.mapNotNull(library::findSongByPath)
val split = fileName.split(".") val name = parsed.name
var newName = split[0] if (name != null) {
// Replace delimiters with space return ImportedPlaylist(name, songs)
newName = newName.replace(Regex("[_-]"), " ") }
// Replace long stretches of whitespace with one space val fileName = filePath.name ?: return ImportedPlaylist(null, songs)
newName = newName.replace(Regex("\\s+"), " ") return ImportedPlaylist(playlistNameFromFileName(fileName), songs)
return ImportedPlaylist(newName, imported.paths)
} }
} catch (e: Exception) { } catch (e: Exception) {
null null
@@ -43,3 +43,13 @@ internal interface PlaylistHandle {
suspend fun delete() suspend fun delete()
} }
/** Derive a playlist name from a file name: strip the extension, delimiters become spaces. */
internal fun playlistNameFromFileName(fileName: String): String {
// Strip extension
var name = fileName.split(".")[0]
// Replace delimiters with space
name = name.replace(Regex("[_-]"), " ")
// Replace long stretches of whitespace with one space
return name.replace(Regex("\\s+"), " ")
}
@@ -0,0 +1,92 @@
/*
* Copyright (c) 2026 Auxio Project
* PlaylistPathResolver.kt is part of Auxio.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.oxycblt.musikr.playlist
import org.oxycblt.musikr.fs.Components
import org.oxycblt.musikr.fs.Path
/**
* Resolves playlist file entries against the indexed library by probe-and-lock: probe entries
* against the candidate roots in order until one resolves, lock that root, then resolve every
* entry against it. All entries in a playlist are assumed to share one root. Absolute entries
* probe with leading components stripped one at a time, which rescues paths written under
* another machine's layout; the locked strip depth then applies to every absolute entry.
*
* Unresolvable entries drop out of the result. A null result means no entry resolved anywhere —
* the only case a playlist fails to resolve.
*
* @author OxygenCobalt (Fork)
*/
internal class PlaylistPathResolver {
/**
* A single playlist entry.
*
* @property components The path as written in the playlist, split into components.
* @property absolute Whether the path was written absolute.
*/
data class Entry(val components: Components, val absolute: Boolean)
/**
* Resolve [entries] against [roots] (in precedence order), using [exists] to test whether a
* resolved path is in the library.
*
* @return The resolved paths in entry order, or null if no entry resolved under any root.
*/
fun resolve(entries: List<Entry>, roots: List<Path>, exists: (Path) -> Boolean): List<Path>? {
var lockedRoot: Path? = null
var lockedStrip = 0
probe@ for (entry in entries) {
// Never strip the file name itself.
val maxStrip = if (entry.absolute) entry.components.components.size - 1 else 0
for (strip in 0..maxStrip) {
for (root in roots) {
val candidate =
Path(root.volume, entry.components.depth(strip).joinedTo(root.components))
if (exists(candidate)) {
lockedRoot = root
lockedStrip = strip
break@probe
}
}
}
}
if (lockedRoot == null) {
return null
}
return entries.mapNotNull { entry ->
val components =
if (entry.absolute) entry.components.depth(lockedStrip) else entry.components
Path(lockedRoot.volume, components.joinedTo(lockedRoot.components)).takeIf(exists)
}
}
/** Join these components onto [base], resolving `.` and `..` segments along the way. */
private fun Components.joinedTo(base: Components): Components {
var result = base
for (component in components) {
result =
when (component) {
".." -> result.parent()
"." -> result
else -> result.child(component)
}
}
return result
}
}
@@ -0,0 +1,86 @@
/*
* Copyright (c) 2026 Auxio Project
* PlaylistReconciler.kt is part of Auxio.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.oxycblt.musikr.playlist
import org.oxycblt.musikr.Music
/**
* Reconciles stored tracked playlists against the playlist files discovered in a scan. The file
* on disk wins when it speaks, but never destructively: an unchanged file keeps the stored
* playlist (in-app edits survive), a changed file with at least one resolved entry replaces it
* (in-app edits are discarded), and a file that is missing or resolves nothing keeps the stored
* playlist. Playlists without a source file are unmanaged and never reach this unit.
*
* @author OxygenCobalt (Fork)
*/
internal object PlaylistReconciler {
/**
* A stored playlist's tracking identity.
*
* @property uid The playlist's UID.
* @property sourceUri The document URI of the file the playlist was imported from.
* @property signature The content signature of that file at import time.
*/
data class Tracked(val uid: Music.UID, val sourceUri: String, val signature: Long)
/**
* A playlist file discovered in a scan.
*
* @property uri The document URI of the file.
* @property signature The content signature of the file.
* @property resolvedCount How many entries resolved against the library.
*/
data class Discovered(val uri: String, val signature: Long, val resolvedCount: Int)
/** What to do with a tracked playlist or discovered file after reconciliation. */
sealed interface Action {
/** Nothing changes: keep the stored playlist as-is. */
data class Keep(val tracked: Tracked) : Action
/** The file changed and resolves: re-import it, replacing the stored playlist's songs. */
data class Replace(val tracked: Tracked, val file: Discovered) : Action
/** The file has no stored playlist and resolves: import it as a new tracked playlist. */
data class Create(val file: Discovered) : Action
}
/**
* Reconcile [tracked] stored playlists against [discovered] files, emitting one [Action] per
* input.
*/
fun reconcile(tracked: List<Tracked>, discovered: List<Discovered>): List<Action> {
val filesByUri = discovered.associateBy { it.uri }
val trackedActions =
tracked.map { item ->
val file = filesByUri[item.sourceUri]
when {
file == null -> Action.Keep(item)
file.signature == item.signature -> Action.Keep(item)
file.resolvedCount == 0 -> Action.Keep(item)
else -> Action.Replace(item, file)
}
}
val trackedUris = tracked.mapTo(mutableSetOf()) { it.sourceUri }
val createActions =
discovered
.filter { it.uri !in trackedUris && it.resolvedCount > 0 }
.map { Action.Create(it) }
return trackedActions + createActions
}
}
@@ -43,7 +43,7 @@ import org.oxycblt.musikr.Music
*/ */
@Database( @Database(
entities = [PlaylistInfo::class, PlaylistSong::class, PlaylistSongCrossRef::class], entities = [PlaylistInfo::class, PlaylistSong::class, PlaylistSongCrossRef::class],
version = 75, version = 76,
exportSchema = false, exportSchema = false,
) )
@TypeConverters(Music.UID.TypeConverters::class) @TypeConverters(Music.UID.TypeConverters::class)
@@ -117,7 +117,15 @@ internal abstract class PlaylistDatabase : RoomDatabase() {
washUids(db, "PlaylistInfo", "playlistUid") washUids(db, "PlaylistInfo", "playlistUid")
washUids(db, "PlaylistSongCrossRef", "playlistUid") washUids(db, "PlaylistSongCrossRef", "playlistUid")
} }
},
object : Migration(75, 76) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE PlaylistInfo ADD COLUMN sourceUri TEXT")
db.execSQL(
"ALTER TABLE PlaylistInfo ADD COLUMN sourceSignature INTEGER"
)
} }
},
) )
.fallbackToDestructiveMigration(true) .fallbackToDestructiveMigration(true)
.build() .build()
@@ -143,6 +151,16 @@ internal abstract class PlaylistDao {
@Query("SELECT * FROM PlaylistInfo") @Query("SELECT * FROM PlaylistInfo")
abstract suspend fun readRawPlaylists(): List<RawPlaylist> abstract suspend fun readRawPlaylists(): List<RawPlaylist>
/** Read the [PlaylistInfo] of playlists with a source file, for reconciliation. */
@Query("SELECT * FROM PlaylistInfo WHERE sourceUri IS NOT NULL AND sourceSignature IS NOT NULL")
abstract suspend fun readTrackedInfos(): List<PlaylistInfo>
/** Update the name and source signature of a tracked playlist after a re-import. */
@Query(
"UPDATE PlaylistInfo SET name = :name, sourceSignature = :signature WHERE playlistUid = :playlistUid"
)
abstract suspend fun updateTrackedInfo(playlistUid: Music.UID, name: String, signature: Long)
/** /**
* Create a new playlist. * Create a new playlist.
* *
@@ -46,7 +46,15 @@ internal data class RawPlaylist(
* *
* @author Alexander Capehart (OxygenCobalt) * @author Alexander Capehart (OxygenCobalt)
*/ */
@Entity internal data class PlaylistInfo(@PrimaryKey val playlistUid: Music.UID, val name: String) @Entity
internal data class PlaylistInfo(
@PrimaryKey val playlistUid: Music.UID,
val name: String,
/** The document URI of the file this playlist was imported from. Null if unmanaged. */
val sourceUri: String? = null,
/** The content signature of the source file at import time. Null if unmanaged. */
val sourceSignature: Long? = null,
)
/** /**
* Song information corresponding to a [RawPlaylist] entry. * Song information corresponding to a [RawPlaylist] entry.
@@ -23,11 +23,32 @@ import org.oxycblt.musikr.Music
import org.oxycblt.musikr.Song import org.oxycblt.musikr.Song
import org.oxycblt.musikr.playlist.PlaylistFile import org.oxycblt.musikr.playlist.PlaylistFile
import org.oxycblt.musikr.playlist.PlaylistHandle import org.oxycblt.musikr.playlist.PlaylistHandle
import org.oxycblt.musikr.playlist.PlaylistReconciler
import org.oxycblt.musikr.playlist.SongPointer import org.oxycblt.musikr.playlist.SongPointer
import org.oxycblt.musikr.util.unlikelyToBeNull
abstract class StoredPlaylists { abstract class StoredPlaylists {
internal abstract suspend fun new(name: String, songs: List<Song>): PlaylistHandle internal abstract suspend fun new(name: String, songs: List<Song>): PlaylistHandle
/** Create a playlist tracked against a source file. */
internal abstract suspend fun newTracked(
name: String,
songUids: List<Music.UID>,
sourceUri: String,
sourceSignature: Long,
): PlaylistHandle
/** Replace a tracked playlist with its re-imported file: new name, songs, and signature. */
internal abstract suspend fun replaceTracked(
playlistUid: Music.UID,
name: String,
songUids: List<Music.UID>,
sourceSignature: Long,
)
/** Read the tracking identities of playlists with a source file. */
internal abstract suspend fun readTracked(): List<PlaylistReconciler.Tracked>
internal abstract suspend fun read(): List<PlaylistFile> internal abstract suspend fun read(): List<PlaylistFile>
companion object { companion object {
@@ -43,6 +64,42 @@ private class StoredPlaylistsImpl(private val playlistDao: PlaylistDao) : Stored
return StoredPlaylistHandle(info, playlistDao) return StoredPlaylistHandle(info, playlistDao)
} }
override suspend fun newTracked(
name: String,
songUids: List<Music.UID>,
sourceUri: String,
sourceSignature: Long,
): PlaylistHandle {
val info =
PlaylistInfo(
Music.UID.auxio(Music.UID.Item.PLAYLIST),
name,
sourceUri = sourceUri,
sourceSignature = sourceSignature,
)
playlistDao.insertPlaylist(RawPlaylist(info, songUids.map { PlaylistSong(it) }))
return StoredPlaylistHandle(info, playlistDao)
}
override suspend fun replaceTracked(
playlistUid: Music.UID,
name: String,
songUids: List<Music.UID>,
sourceSignature: Long,
) {
playlistDao.replacePlaylistSongs(playlistUid, songUids.map { PlaylistSong(it) })
playlistDao.updateTrackedInfo(playlistUid, name, sourceSignature)
}
override suspend fun readTracked() =
playlistDao.readTrackedInfos().map {
PlaylistReconciler.Tracked(
it.playlistUid,
unlikelyToBeNull(it.sourceUri),
unlikelyToBeNull(it.sourceSignature),
)
}
override suspend fun read() = override suspend fun read() =
playlistDao.readRawPlaylists().map { playlistDao.readRawPlaylists().map {
PlaylistFile( PlaylistFile(
@@ -18,7 +18,6 @@
package org.oxycblt.musikr.playlist.m3u package org.oxycblt.musikr.playlist.m3u
import android.content.Context
import java.io.BufferedReader import java.io.BufferedReader
import java.io.BufferedWriter import java.io.BufferedWriter
import java.io.InputStream import java.io.InputStream
@@ -27,11 +26,8 @@ import java.io.OutputStream
import org.oxycblt.musikr.Playlist import org.oxycblt.musikr.Playlist
import org.oxycblt.musikr.fs.Components import org.oxycblt.musikr.fs.Components
import org.oxycblt.musikr.fs.Path import org.oxycblt.musikr.fs.Path
import org.oxycblt.musikr.fs.Volume
import org.oxycblt.musikr.fs.path.VolumeManager
import org.oxycblt.musikr.playlist.ExportConfig import org.oxycblt.musikr.playlist.ExportConfig
import org.oxycblt.musikr.playlist.ImportedPlaylist import org.oxycblt.musikr.playlist.PlaylistPathResolver
import org.oxycblt.musikr.playlist.PossiblePaths
import org.oxycblt.musikr.tag.Name import org.oxycblt.musikr.tag.Name
import org.oxycblt.musikr.util.correctWhitespace import org.oxycblt.musikr.util.correctWhitespace
import org.oxycblt.musikr.util.unlikelyToBeNull import org.oxycblt.musikr.util.unlikelyToBeNull
@@ -43,15 +39,13 @@ import org.oxycblt.musikr.util.unlikelyToBeNull
*/ */
abstract class M3U { abstract class M3U {
/** /**
* Reads an M3U file from the given [stream] and returns a [ImportedPlaylist] containing the * Reads an M3U file from the given [stream] and returns the parsed [ParsedM3U]. Entries are
* paths to the files listed in the M3U file. * interpreted but not resolved against the library — see [PlaylistPathResolver].
* *
* @param stream The stream to read the M3U file from. * @param stream The stream to read the M3U file from.
* @param workingDirectory The directory that the M3U file is contained in. This is used to * @return The [ParsedM3U], or null if the file contained no entries.
* resolve relative paths.
* @return An [ImportedPlaylist] containing the paths to the files listed in the M3U file,
*/ */
internal abstract fun read(stream: InputStream, workingDirectory: Path): ImportedPlaylist? internal abstract fun read(stream: InputStream): ParsedM3U?
/** /**
* Writes the given [playlist] to the given [outputStream] in the M3U format,. * Writes the given [playlist] to the given [outputStream] in the M3U format,.
@@ -73,15 +67,22 @@ abstract class M3U {
/** The mime type used for M3U files by the android system. */ /** The mime type used for M3U files by the android system. */
const val MIME_TYPE = "audio/x-mpegurl" const val MIME_TYPE = "audio/x-mpegurl"
internal fun from(context: Context): M3U = M3UImpl(VolumeManager.from(context)) internal fun new(): M3U = M3UImpl()
} }
} }
private class M3UImpl(private val volumeManager: VolumeManager) : M3U() { /**
override fun read(stream: InputStream, workingDirectory: Path): ImportedPlaylist? { * The raw result of parsing an M3U file.
val volumes = volumeManager.getVolumes() *
* @property name The playlist name, if a #PLAYLIST entry was present.
* @property entries The parsed entries in file order.
*/
internal data class ParsedM3U(val name: String?, val entries: List<PlaylistPathResolver.Entry>)
private class M3UImpl : M3U() {
override fun read(stream: InputStream): ParsedM3U? {
val reader = BufferedReader(InputStreamReader(stream)) val reader = BufferedReader(InputStreamReader(stream))
val paths = mutableListOf<PossiblePaths>() val entries = mutableListOf<PlaylistPathResolver.Entry>()
var name: String? = null var name: String? = null
consumeFile@ while (true) { consumeFile@ while (true) {
@@ -112,61 +113,41 @@ private class M3UImpl(private val volumeManager: VolumeManager) : M3U() {
} }
} }
// There is basically no formal specification of file paths in M3U, and it differs // One interpretation per line: resolution against the library happens later, in
// based on the programs that generated it. I more or less have to consider any possible // PlaylistPathResolver.
// interpretation as valid. entries.add(interpretLine(unlikelyToBeNull(path)))
val interpretations = interpretPath(unlikelyToBeNull(path))
val possibilities = interpretations.flatMap {
expandInterpretation(it, workingDirectory, volumes)
} }
paths.add(possibilities) return if (entries.isNotEmpty()) {
} ParsedM3U(name, entries)
return if (paths.isNotEmpty()) {
ImportedPlaylist(name, paths)
} else { } else {
// Couldn't get anything useful out of this file. // Couldn't get anything useful out of this file.
null null
} }
} }
private data class InterpretedPath(val components: Components, val likelyAbsolute: Boolean) /**
* Interpret a line as an entry. There is no formal specification of M3U paths, so the form
private fun interpretPath(path: String): List<InterpretedPath> = * detection is heuristic: unix or windows, absolute or relative. Bare lines parse by
* whichever separator they contain.
*/
private fun interpretLine(path: String): PlaylistPathResolver.Entry =
when { when {
path.startsWith('/') -> listOf(InterpretedPath(Components.parseUnix(path), true)) path.startsWith('/') ->
path.startsWith("./") -> listOf(InterpretedPath(Components.parseUnix(path), false)) PlaylistPathResolver.Entry(Components.parseUnix(path), absolute = true)
path.startsWith("./") ->
PlaylistPathResolver.Entry(Components.parseUnix(path), absolute = false)
path.matches(WINDOWS_VOLUME_PREFIX_REGEX) -> path.matches(WINDOWS_VOLUME_PREFIX_REGEX) ->
listOf(InterpretedPath(Components.parseWindows(path.substring(2)), true)) PlaylistPathResolver.Entry(
path.startsWith("\\") -> listOf(InterpretedPath(Components.parseWindows(path), true)) Components.parseWindows(path.substring(2)), absolute = true
path.startsWith(".\\") -> listOf(InterpretedPath(Components.parseWindows(path), false))
else ->
listOf(
InterpretedPath(Components.parseUnix(path), false),
InterpretedPath(Components.parseWindows(path), true),
) )
} path.startsWith("\\") ->
PlaylistPathResolver.Entry(Components.parseWindows(path), absolute = true)
private fun expandInterpretation( path.startsWith(".\\") ->
path: InterpretedPath, PlaylistPathResolver.Entry(Components.parseWindows(path), absolute = false)
workingDirectory: Path, '\\' in path ->
volumes: List<Volume>, PlaylistPathResolver.Entry(Components.parseWindows(path), absolute = false)
): List<Path> { else -> PlaylistPathResolver.Entry(Components.parseUnix(path), absolute = false)
val absoluteInterpretation = Path(workingDirectory.volume, path.components)
val relativeInterpretation =
Path(workingDirectory.volume, path.components.absoluteTo(workingDirectory.components))
val volumeExactMatch = volumes.find { it.components?.contains(path.components) == true }
val volumeInterpretation = volumeExactMatch?.let {
val components =
unlikelyToBeNull(volumeExactMatch.components).containing(path.components)
Path(volumeExactMatch, components)
}
return if (path.likelyAbsolute) {
listOfNotNull(volumeInterpretation, absoluteInterpretation, relativeInterpretation)
} else {
listOfNotNull(relativeInterpretation, volumeInterpretation, absoluteInterpretation)
}
} }
override fun write( override fun write(
@@ -232,22 +213,6 @@ private class M3UImpl(private val volumeManager: VolumeManager) : M3U() {
newLine() newLine()
} }
private fun Components.absoluteTo(workingDirectory: Components): Components {
var absoluteComponents = workingDirectory
for (component in components) {
when (component) {
// Parent specifier, go "back" one directory (in practice cleave off the last
// component)
".." -> absoluteComponents = absoluteComponents.parent()
// Current directory, the components are already there.
"." -> {}
// New directory, add it
else -> absoluteComponents = absoluteComponents.child(component)
}
}
return absoluteComponents
}
private fun Components.relativeTo(workingDirectory: Components): Components { private fun Components.relativeTo(workingDirectory: Components): Components {
// We want to find the common prefix of the working directory and path, and then // We want to find the common prefix of the working directory and path, and then
// and them combine them with the correct relative elements to make sure they // and them combine them with the correct relative elements to make sure they
@@ -253,15 +253,18 @@ internal fun Metadata.isCompilation() =
?: id3v2["TXXX:COMPILATION"] ?: id3v2["TXXX:COMPILATION"]
?: id3v2["TXXX:ITUNESCOMPILATION"]) == listOf("1") ?: id3v2["TXXX:ITUNESCOMPILATION"]) == listOf("1")
// ReplayGain information // ReplayGain information. APE is preferred over the other tag formats: it is the only ReplayGain
// carrier in some libraries, and where it coexists with ID3v2 it is the more deliberate choice.
internal fun Metadata.replayGainTrackAdjustment() = internal fun Metadata.replayGainTrackAdjustment() =
(xiph["R128_TRACK_GAIN"]?.parseR128Adjustment() (ape["REPLAYGAIN_TRACK_GAIN"]?.parseReplayGainAdjustment()
?: xiph["R128_TRACK_GAIN"]?.parseR128Adjustment()
?: xiph["REPLAYGAIN_TRACK_GAIN"]?.parseReplayGainAdjustment() ?: xiph["REPLAYGAIN_TRACK_GAIN"]?.parseReplayGainAdjustment()
?: mp4["----:COM.APPLE.ITUNES:REPLAYGAIN_TRACK_GAIN"]?.parseReplayGainAdjustment() ?: mp4["----:COM.APPLE.ITUNES:REPLAYGAIN_TRACK_GAIN"]?.parseReplayGainAdjustment()
?: id3v2["TXXX:REPLAYGAIN_TRACK_GAIN"]?.parseReplayGainAdjustment()) ?: id3v2["TXXX:REPLAYGAIN_TRACK_GAIN"]?.parseReplayGainAdjustment())
internal fun Metadata.replayGainAlbumAdjustment() = internal fun Metadata.replayGainAlbumAdjustment() =
(xiph["R128_ALBUM_GAIN"]?.parseR128Adjustment() (ape["REPLAYGAIN_ALBUM_GAIN"]?.parseReplayGainAdjustment()
?: xiph["R128_ALBUM_GAIN"]?.parseR128Adjustment()
?: xiph["REPLAYGAIN_ALBUM_GAIN"]?.parseReplayGainAdjustment() ?: xiph["REPLAYGAIN_ALBUM_GAIN"]?.parseReplayGainAdjustment()
?: mp4["----:COM.APPLE.ITUNES:REPLAYGAIN_ALBUM_GAIN"]?.parseReplayGainAdjustment() ?: mp4["----:COM.APPLE.ITUNES:REPLAYGAIN_ALBUM_GAIN"]?.parseReplayGainAdjustment()
?: id3v2["TXXX:REPLAYGAIN_ALBUM_GAIN"]?.parseReplayGainAdjustment()) ?: id3v2["TXXX:REPLAYGAIN_ALBUM_GAIN"]?.parseReplayGainAdjustment())
@@ -0,0 +1,302 @@
/*
* Copyright (c) 2026 Auxio Project
* PlaylistPathResolverTest.kt is part of Auxio.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.oxycblt.musikr.playlist
import android.content.Context
import org.junit.Assert.assertEquals
import org.junit.Test
import org.oxycblt.musikr.fs.Components
import org.oxycblt.musikr.fs.Path
import org.oxycblt.musikr.fs.Volume
class PlaylistPathResolverTest {
@Test
fun resolve_relativeEntries_locksMusicLocationRoot() {
val volume = FakeVolume()
val playlistDir = Path(volume, Components.parseUnix("Music/Playlists"))
val musicRoot = Path(volume, Components.parseUnix("Music"))
val library =
setOf(
Path(volume, Components.parseUnix("Music/Library/Artist/a.mp3")),
Path(volume, Components.parseUnix("Music/Library/Artist/b.mp3")),
)
val entries =
listOf(
PlaylistPathResolver.Entry(
Components.parseUnix("Library/Artist/a.mp3"), absolute = false
),
PlaylistPathResolver.Entry(
Components.parseUnix("Library/Artist/b.mp3"), absolute = false
),
)
val resolved =
PlaylistPathResolver().resolve(entries, listOf(playlistDir, musicRoot)) {
it in library
}
assertEquals(
listOf(
Path(volume, Components.parseUnix("Music/Library/Artist/a.mp3")),
Path(volume, Components.parseUnix("Music/Library/Artist/b.mp3")),
),
resolved,
)
}
@Test
fun resolve_dotPrefixedEntries_resolveLikeBareOnes() {
val volume = FakeVolume()
val playlistDir = Path(volume, Components.parseUnix("Music/Playlists"))
val musicRoot = Path(volume, Components.parseUnix("Music"))
val library =
setOf(
Path(volume, Components.parseUnix("Music/Library/Artist/a.mp3")),
Path(volume, Components.parseUnix("Music/Library/Artist/b.mp3")),
)
val entries =
listOf(
PlaylistPathResolver.Entry(
Components.parseUnix("./Library/Artist/a.mp3"), absolute = false
),
PlaylistPathResolver.Entry(
Components.parseUnix("./Library/Artist/b.mp3"), absolute = false
),
)
val resolved =
PlaylistPathResolver().resolve(entries, listOf(playlistDir, musicRoot)) {
it in library
}
assertEquals(
listOf(
Path(volume, Components.parseUnix("Music/Library/Artist/a.mp3")),
Path(volume, Components.parseUnix("Music/Library/Artist/b.mp3")),
),
resolved,
)
}
@Test
fun resolve_dotdotEntries_escapeThePlaylistDirectory() {
val volume = FakeVolume()
val playlistDir = Path(volume, Components.parseUnix("Music/Playlists"))
val musicRoot = Path(volume, Components.parseUnix("Music"))
val library =
setOf(
Path(volume, Components.parseUnix("Music/Library/Artist/a.mp3")),
Path(volume, Components.parseUnix("Music/Library/Artist/b.mp3")),
)
val entries =
listOf(
PlaylistPathResolver.Entry(
Components.parseUnix("../Library/Artist/a.mp3"), absolute = false
),
PlaylistPathResolver.Entry(
Components.parseUnix("../Library/Artist/b.mp3"), absolute = false
),
)
val resolved =
PlaylistPathResolver().resolve(entries, listOf(playlistDir, musicRoot)) {
it in library
}
assertEquals(
listOf(
Path(volume, Components.parseUnix("Music/Library/Artist/a.mp3")),
Path(volume, Components.parseUnix("Music/Library/Artist/b.mp3")),
),
resolved,
)
}
@Test
fun resolve_ambiguousEntries_lockTheFirstRootInOrder() {
val volume = FakeVolume()
val playlistDir = Path(volume, Components.parseUnix("Music/Playlists"))
val musicRoot = Path(volume, Components.parseUnix("Music"))
val library =
setOf(
Path(volume, Components.parseUnix("Music/Playlists/Library/Artist/a.mp3")),
Path(volume, Components.parseUnix("Music/Library/Artist/a.mp3")),
)
val entries =
listOf(
PlaylistPathResolver.Entry(
Components.parseUnix("Library/Artist/a.mp3"), absolute = false
)
)
val resolved =
PlaylistPathResolver().resolve(entries, listOf(playlistDir, musicRoot)) {
it in library
}
assertEquals(
listOf(Path(volume, Components.parseUnix("Music/Playlists/Library/Artist/a.mp3"))),
resolved,
)
}
@Test
fun resolve_foreignAbsoluteEntries_stripLeadingSegmentsToLock() {
val volume = FakeVolume()
val playlistDir = Path(volume, Components.parseUnix("Music/Playlists"))
val musicRoot = Path(volume, Components.parseUnix("Music"))
val library =
setOf(
Path(volume, Components.parseUnix("Music/Library/Artist/a.mp3")),
Path(volume, Components.parseUnix("Music/Library/Artist/b.mp3")),
)
// Written on another machine: C:\Users\me\Music\... with the volume prefix consumed.
val entries =
listOf(
PlaylistPathResolver.Entry(
Components.parseWindows("Users\\me\\Music\\Library\\Artist\\a.mp3"),
absolute = true,
),
PlaylistPathResolver.Entry(
Components.parseWindows("Users\\me\\Music\\Library\\Artist\\b.mp3"),
absolute = true,
),
)
val resolved =
PlaylistPathResolver().resolve(entries, listOf(playlistDir, musicRoot)) {
it in library
}
assertEquals(
listOf(
Path(volume, Components.parseUnix("Music/Library/Artist/a.mp3")),
Path(volume, Components.parseUnix("Music/Library/Artist/b.mp3")),
),
resolved,
)
}
@Test
fun resolve_partiallyMissingEntries_resolveTheSurvivors() {
val volume = FakeVolume()
val playlistDir = Path(volume, Components.parseUnix("Music/Playlists"))
val musicRoot = Path(volume, Components.parseUnix("Music"))
val library =
setOf(
Path(volume, Components.parseUnix("Music/Library/Artist/a.mp3")),
Path(volume, Components.parseUnix("Music/Library/Artist/c.mp3")),
)
val entries =
listOf(
PlaylistPathResolver.Entry(
Components.parseUnix("Library/Artist/a.mp3"), absolute = false
),
PlaylistPathResolver.Entry(
Components.parseUnix("Library/Artist/b.mp3"), absolute = false
),
PlaylistPathResolver.Entry(
Components.parseUnix("Library/Artist/c.mp3"), absolute = false
),
)
val resolved =
PlaylistPathResolver().resolve(entries, listOf(playlistDir, musicRoot)) {
it in library
}
assertEquals(
listOf(
Path(volume, Components.parseUnix("Music/Library/Artist/a.mp3")),
Path(volume, Components.parseUnix("Music/Library/Artist/c.mp3")),
),
resolved,
)
}
@Test
fun resolve_firstEntryMissing_probeAdvancesAndLocks() {
val volume = FakeVolume()
val playlistDir = Path(volume, Components.parseUnix("Music/Playlists"))
val musicRoot = Path(volume, Components.parseUnix("Music"))
val library =
setOf(
Path(volume, Components.parseUnix("Music/Library/Artist/b.mp3")),
Path(volume, Components.parseUnix("Music/Library/Artist/c.mp3")),
)
val entries =
listOf(
PlaylistPathResolver.Entry(
Components.parseUnix("Library/Artist/a.mp3"), absolute = false
),
PlaylistPathResolver.Entry(
Components.parseUnix("Library/Artist/b.mp3"), absolute = false
),
PlaylistPathResolver.Entry(
Components.parseUnix("Library/Artist/c.mp3"), absolute = false
),
)
val resolved =
PlaylistPathResolver().resolve(entries, listOf(playlistDir, musicRoot)) {
it in library
}
assertEquals(
listOf(
Path(volume, Components.parseUnix("Music/Library/Artist/b.mp3")),
Path(volume, Components.parseUnix("Music/Library/Artist/c.mp3")),
),
resolved,
)
}
@Test
fun resolve_unresolvableEntries_failAsNull() {
val volume = FakeVolume()
val playlistDir = Path(volume, Components.parseUnix("Music/Playlists"))
val musicRoot = Path(volume, Components.parseUnix("Music"))
val library =
setOf(Path(volume, Components.parseUnix("Music/Library/Artist/a.mp3")))
val entries =
listOf(
PlaylistPathResolver.Entry(
Components.parseUnix("Elsewhere/Artist/x.mp3"), absolute = false
),
PlaylistPathResolver.Entry(
Components.parseUnix("Elsewhere/Artist/y.mp3"), absolute = false
),
)
val resolved =
PlaylistPathResolver().resolve(entries, listOf(playlistDir, musicRoot)) {
it in library
}
assertEquals(null, resolved)
}
private class FakeVolume : Volume.External {
override val mediaStoreName = "fake"
override val id = "fake"
override val components = Components.parseUnix("storage/emulated/0")
override fun resolveName(context: Context) = "fake"
}
}
@@ -0,0 +1,92 @@
/*
* Copyright (c) 2026 Auxio Project
* PlaylistReconcilerTest.kt is part of Auxio.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.oxycblt.musikr.playlist
import org.junit.Assert.assertEquals
import org.junit.Test
import org.oxycblt.musikr.Music
class PlaylistReconcilerTest {
@Test
fun reconcile_unchangedFile_keepsTheStoredPlaylist() {
val tracked = tracked(42L)
val discovered = discovered(42L, resolvedCount = 1)
val actions = PlaylistReconciler.reconcile(listOf(tracked), listOf(discovered))
assertEquals(listOf(PlaylistReconciler.Action.Keep(tracked)), actions)
}
@Test
fun reconcile_changedFile_replacesTheStoredPlaylist() {
val tracked = tracked(42L)
val discovered = discovered(43L, resolvedCount = 1)
val actions = PlaylistReconciler.reconcile(listOf(tracked), listOf(discovered))
assertEquals(listOf(PlaylistReconciler.Action.Replace(tracked, discovered)), actions)
}
@Test
fun reconcile_deletedFile_keepsTheStoredPlaylist() {
val tracked = tracked(42L)
val actions = PlaylistReconciler.reconcile(listOf(tracked), emptyList())
assertEquals(listOf(PlaylistReconciler.Action.Keep(tracked)), actions)
}
@Test
fun reconcile_changedFileWithNothingResolved_keepsTheStoredPlaylist() {
val tracked = tracked(42L)
val discovered = discovered(43L, resolvedCount = 0)
val actions = PlaylistReconciler.reconcile(listOf(tracked), listOf(discovered))
assertEquals(listOf(PlaylistReconciler.Action.Keep(tracked)), actions)
}
@Test
fun reconcile_newFile_createsATrackedPlaylist() {
val discovered = discovered(42L, resolvedCount = 1)
val actions = PlaylistReconciler.reconcile(emptyList(), listOf(discovered))
assertEquals(listOf(PlaylistReconciler.Action.Create(discovered)), actions)
}
@Test
fun reconcile_newFileWithNothingResolved_doesNothing() {
val discovered = discovered(42L, resolvedCount = 0)
val actions = PlaylistReconciler.reconcile(emptyList(), listOf(discovered))
assertEquals(emptyList<PlaylistReconciler.Action>(), actions)
}
private fun tracked(signature: Long) =
PlaylistReconciler.Tracked(
Music.UID.auxio(Music.UID.Item.PLAYLIST),
"content://tree/playlists/x.m3u",
signature,
)
private fun discovered(signature: Long, resolvedCount: Int) =
PlaylistReconciler.Discovered("content://tree/playlists/x.m3u", signature, resolvedCount)
}
@@ -0,0 +1,70 @@
/*
* Copyright (c) 2026 Auxio Project
* M3UTest.kt is part of Auxio.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.oxycblt.musikr.playlist.m3u
import org.junit.Assert.assertEquals
import org.junit.Test
import org.oxycblt.musikr.fs.Components
import org.oxycblt.musikr.playlist.PlaylistPathResolver
class M3UTest {
@Test
fun read_relativeAndForeignAbsoluteLines_produceEntries() {
val text =
"""
#EXTM3U
Library/Artist/a.mp3
./Library/Artist/b.mp3
C:\Users\me\Music\Library\Artist\c.mp3
"""
.trimIndent()
val imported = M3U.new().read(text.byteInputStream())
assertEquals(
listOf(
PlaylistPathResolver.Entry(
Components.parseUnix("Library/Artist/a.mp3"), absolute = false
),
PlaylistPathResolver.Entry(
Components.parseUnix("./Library/Artist/b.mp3"), absolute = false
),
PlaylistPathResolver.Entry(
Components.parseUnix("Users/me/Music/Library/Artist/c.mp3"), absolute = true
),
),
imported?.entries,
)
}
@Test
fun read_playlistMetadata_producesName() {
val text =
"""
#EXTM3U
#PLAYLIST:My Mix
Library/Artist/a.mp3
"""
.trimIndent()
val imported = M3U.new().read(text.byteInputStream())
assertEquals("My Mix", imported?.name)
}
}
@@ -321,10 +321,22 @@ class TagFieldsTest {
assertEquals(listOf("Classical", "Ambient"), metadata.genreNames()) assertEquals(listOf("Classical", "Ambient"), metadata.genreNames())
} }
@Test
fun metadata_replayGainTrack_apePreferredOverId3v2() {
val metadata =
createTestMetadata(
id3v2Tags = mapOf("TXXX:REPLAYGAIN_TRACK_GAIN" to listOf("-1.0 dB")),
apeTags = mapOf("REPLAYGAIN_TRACK_GAIN" to listOf("-5.175 dB")),
)
assertEquals(-5.175f, metadata.replayGainTrackAdjustment()!!, 0.0001f)
}
private fun createTestMetadata( private fun createTestMetadata(
id3v2Tags: Map<String, List<String>> = emptyMap(), id3v2Tags: Map<String, List<String>> = emptyMap(),
xiphTags: Map<String, List<String>> = emptyMap(), xiphTags: Map<String, List<String>> = emptyMap(),
mp4Tags: Map<String, List<String>> = emptyMap(), mp4Tags: Map<String, List<String>> = emptyMap(),
apeTags: Map<String, List<String>> = emptyMap(),
cover: ByteArray? = null, cover: ByteArray? = null,
durationMs: Long = 1000, durationMs: Long = 1000,
bitrateKbps: Int = 320, bitrateKbps: Int = 320,
@@ -332,6 +344,6 @@ class TagFieldsTest {
mimeType: String = "audio/mpeg", mimeType: String = "audio/mpeg",
): Metadata { ): Metadata {
val properties = Properties(mimeType, durationMs, bitrateKbps, sampleRateHz) val properties = Properties(mimeType, durationMs, bitrateKbps, sampleRateHz)
return Metadata(id3v2Tags, xiphTags, mp4Tags, cover, properties) return Metadata(id3v2Tags, xiphTags, mp4Tags, apeTags, cover, properties)
} }
} }
@@ -185,6 +185,6 @@ class TagParserTest {
mimeType: String = "audio/mpeg", mimeType: String = "audio/mpeg",
): Metadata { ): Metadata {
val properties = Properties(mimeType, durationMs, bitrateKbps, sampleRateHz) val properties = Properties(mimeType, durationMs, bitrateKbps, sampleRateHz)
return Metadata(id3v2Tags, xiphTags, mp4Tags, cover, properties) return Metadata(id3v2Tags, xiphTags, mp4Tags, emptyMap(), cover, properties)
} }
} }
@@ -243,6 +243,6 @@ class TagParsingEdgeCasesTest {
mimeType: String = "audio/mpeg", mimeType: String = "audio/mpeg",
): Metadata { ): Metadata {
val properties = Properties(mimeType, durationMs, bitrateKbps, sampleRateHz) val properties = Properties(mimeType, durationMs, bitrateKbps, sampleRateHz)
return Metadata(id3v2Tags, xiphTags, mp4Tags, cover, properties) return Metadata(id3v2Tags, xiphTags, mp4Tags, emptyMap(), cover, properties)
} }
} }