musikr: fix invalid graph by invalid mbid setup

This commit is contained in:
Alexander Capehart
2025-08-14 15:05:52 -06:00
parent 61e7b18918
commit 8603731eff
9 changed files with 272 additions and 72 deletions
@@ -19,6 +19,7 @@
package org.oxycblt.musikr
import android.content.Context
import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.coroutineScope
@@ -69,7 +70,7 @@ interface Musikr {
config,
ExploreStep.from(context, config),
ExtractStep.from(context, config),
EvaluateStep.new(config, config.interpretation))
EvaluateStep.new(context, config, config.interpretation))
}
}
@@ -141,6 +142,7 @@ private class MusikrImpl(
}
val library = evaluateStep.evaluate(trackedExtractedChannel)
merge(exploredTask, extractedTask, trackedExploredTask, trackedExtractedTask).await()
Log.d("Musikr", "Indexing took ${System.currentTimeMillis() - start}ms")
LibraryResultImpl(config, library)
}
}
@@ -89,6 +89,7 @@ class Compress(
"Failed to decode bitmap"
}
bitmap.compress(format, quality, output)
bitmap.recycle()
true
}
}
@@ -18,6 +18,8 @@
package org.oxycblt.musikr.graph
import android.content.Context
import java.io.File
import org.oxycblt.musikr.Music
import org.oxycblt.musikr.playlist.SongPointer
import org.oxycblt.musikr.playlist.interpret.PrePlaylist
@@ -27,6 +29,7 @@ import org.oxycblt.musikr.tag.interpret.PreArtistsFrom
import org.oxycblt.musikr.tag.interpret.PreGenre
import org.oxycblt.musikr.tag.interpret.PreSong
import org.oxycblt.musikr.util.unlikelyToBeNull
import java.util.UUID
internal data class MusicGraph(
val songVertex: List<SongVertex>,
@@ -46,6 +49,133 @@ internal data class MusicGraph(
companion object {
fun builder(): Builder = MusicGraphBuilderImpl()
}
fun renderToGraphviz(context: Context, fileName: String = "music_graph.dot") {
val dot = buildString {
appendLine("digraph MusicGraph {")
appendLine(" rankdir=LR;")
appendLine(" node [shape=rectangle];")
appendLine()
// Define node styles for different vertex types
appendLine(" // Songs")
appendLine(" node [style=filled,fillcolor=lightblue];")
songVertex.forEachIndexed { index, song ->
val songId = "song_$index"
val name = song.preSong.rawName ?: "Unknown Song"
val uid = song.preSong.v401Uid
val label = "${escape(name)}\\nUID: $uid"
appendLine(" $songId [label=\"$label\"];")
}
appendLine()
appendLine(" // Albums")
appendLine(" node [style=filled,fillcolor=lightgreen];")
albumVertex.forEachIndexed { index, album ->
val albumId = "album_$index"
val name = album.preAlbum.rawName ?: "Unknown Album"
val mbid = album.preAlbum.musicBrainzId?.let { "\\nMBID: $it" } ?: ""
val label = "${escape(name)}$mbid"
appendLine(" $albumId [label=\"$label\"];")
}
appendLine()
appendLine(" // Artists")
appendLine(" node [style=filled,fillcolor=lightyellow];")
artistVertex.forEachIndexed { index, artist ->
val artistId = "artist_$index"
val name = artist.preArtist.rawName ?: "Unknown Artist"
val mbid = artist.preArtist.musicBrainzId?.let { "\\nMBID: $it" } ?: ""
val label = "${escape(name)}$mbid"
appendLine(" $artistId [label=\"$label\"];")
}
appendLine()
appendLine(" // Genres")
appendLine(" node [style=filled,fillcolor=lightcoral];")
genreVertex.forEachIndexed { index, genre ->
val genreId = "genre_$index"
val label = genre.preGenre.rawName ?: "Unknown Genre"
appendLine(" $genreId [label=\"${escape(label)}\"];")
}
appendLine()
appendLine(" // Playlists")
appendLine(" node [style=filled,fillcolor=lavender];")
playlistVertex.forEachIndexed { index, playlist ->
val playlistId = "playlist_$index"
val label = playlist.prePlaylist.rawName ?: "Unknown Playlist"
appendLine(" $playlistId [label=\"${escape(label)}\"];")
}
appendLine()
// Create edges
appendLine(" // Song -> Album edges")
songVertex.forEachIndexed { songIndex, song ->
val albumIndex = albumVertex.indexOf(song.albumVertex)
if (albumIndex >= 0) {
appendLine(" song_$songIndex -> album_$albumIndex [color=blue];")
}
}
appendLine()
appendLine(" // Song -> Artist edges")
songVertex.forEachIndexed { songIndex, song ->
song.artistVertices.forEach { artistVertex ->
val artistIndex = this@MusicGraph.artistVertex.indexOf(artistVertex)
if (artistIndex >= 0) {
appendLine(" song_$songIndex -> artist_$artistIndex [color=green];")
}
}
}
appendLine()
appendLine(" // Song -> Genre edges")
songVertex.forEachIndexed { songIndex, song ->
song.genreVertices.forEach { genreVertex ->
val genreIndex = this@MusicGraph.genreVertex.indexOf(genreVertex)
if (genreIndex >= 0) {
appendLine(" song_$songIndex -> genre_$genreIndex [color=red];")
}
}
}
appendLine()
appendLine(" // Album -> Artist edges")
albumVertex.forEachIndexed { albumIndex, album ->
album.artistVertices.forEach { artistVertex ->
val artistIndex = this@MusicGraph.artistVertex.indexOf(artistVertex)
if (artistIndex >= 0) {
appendLine(" album_$albumIndex -> artist_$artistIndex [color=purple];")
}
}
}
appendLine()
appendLine(" // Playlist -> Song edges")
playlistVertex.forEachIndexed { playlistIndex, playlist ->
playlist.songVertices.forEachIndexed { _, songVertex ->
songVertex?.let {
val songIndex = this@MusicGraph.songVertex.indexOf(it)
if (songIndex >= 0) {
appendLine(
" playlist_$playlistIndex -> song_$songIndex [color=orange];")
}
}
}
}
appendLine("}")
}
// Write to internal storage
val file = File(context.filesDir, fileName)
file.writeText(dot)
}
private fun escape(text: String, maxLength: Int = 50): String {
return text.replace("\"", "\\\"").replace("\n", "\\n").replace("\r", "\\r").take(maxLength)
}
}
private class MusicGraphBuilderImpl : MusicGraph.Builder {
@@ -119,15 +249,56 @@ private class MusicGraphBuilderImpl : MusicGraph.Builder {
simplifyGenreCluster(cluster)
}
// first pass: cluster artists by name and process MBIDs where valid
val artistClusters = artistVertices.values.groupBy { it.preArtist.rawName?.lowercase() }
for (cluster in artistClusters.values) {
simplifyArtistCluster(cluster)
}
// second pass: cluster artists by mbid and identify invalid ones
// (i.e artists with the same mbid but different metdata)
val mbidClusters =
artistVertices.values.groupBy { it.preArtist.musicBrainzId }
for (cluster in mbidClusters.values) {
// everything in the cluster must have the same pre-artist
val canon = cluster.maxBy { it.songVertices.size }.preArtist
val same = cluster.all { it.preArtist == canon }
if (!same) {
// invalid mbid setup, strip mbids from all artists in the cluster
val noMbidPreArtist = canon.copy(musicBrainzId = null)
val simpleMbidVertex =
artistVertices.getOrPut(noMbidPreArtist) { ArtistVertex(noMbidPreArtist) }
for (artist in cluster) {
meldArtistVertices(artist, simpleMbidVertex)
}
}
}
// first pass: cluster albums by name and process MBIDs where valid
val albumClusters = albumVertices.values.groupBy { it.preAlbum.rawName?.lowercase() }
for (cluster in albumClusters.values) {
simplifyAlbumCluster(cluster)
}
// second pass: cluster albums by mbid and identify invalid ones
// (i.e albums with the same mbid but different metadata)
val mbidAlbumClusters =
albumVertices.values.groupBy { it.preAlbum.musicBrainzId }
for (cluster in mbidAlbumClusters.values) {
// everything in the cluster must have the same pre-album
val canon = cluster.maxBy { it.songVertices.size }.preAlbum
val same = cluster.all { it.preAlbum == canon }
if (!same) {
// invalid mbid setup, strip mbids from all albums in the cluster
val noMbidPreAlbum = canon.copy(musicBrainzId = null)
val simpleMbidVertex =
albumVertices.getOrPut(noMbidPreAlbum) {
AlbumVertex(noMbidPreAlbum, mutableListOf())
}
for (album in cluster) {
meldAlbumVertices(album, simpleMbidVertex)
}
}
}
// Remove any edges that wound up connecting to the same artist or genre
// in the end after simplification.
@@ -18,6 +18,7 @@
package org.oxycblt.musikr.model
import android.util.Log
import org.oxycblt.musikr.Album
import org.oxycblt.musikr.Artist
import org.oxycblt.musikr.Genre
@@ -44,7 +45,7 @@ internal class ArtistImpl(private val core: ArtistCore) : Artist {
override val uid =
// Attempt to use a MusicBrainz ID first before falling back to a hashed UID.
core.preArtist.musicBrainzId?.let { Music.UID.musicBrainz(Music.UID.Item.ARTIST, it) }
?: Music.UID.auxio(Music.UID.Item.ARTIST) { update(core.preArtist.rawName) }
?: Music.UID.auxio(Music.UID.Item.ARTIST) { update(core.preArtist.rawName.also { Log.d("ArtistImpl", it.toString()) }) }
override val name = core.preArtist.name
override val songs = core.songs
@@ -18,7 +18,10 @@
package org.oxycblt.musikr.pipeline
import android.content.Context
import android.util.Log
import kotlinx.coroutines.channels.Channel
import org.oxycblt.musikr.BuildConfig
import org.oxycblt.musikr.Config
import org.oxycblt.musikr.Interpretation
import org.oxycblt.musikr.MutableLibrary
@@ -32,8 +35,9 @@ internal interface EvaluateStep {
suspend fun evaluate(extractedMusic: Channel<Extracted>): MutableLibrary
companion object {
fun new(config: Config, interpretation: Interpretation): EvaluateStep =
fun new(context: Context, config: Config, interpretation: Interpretation): EvaluateStep =
EvaluateStepImpl(
context,
TagInterpreter.new(interpretation),
PlaylistInterpreter.new(interpretation),
config.storage.storedPlaylists,
@@ -42,6 +46,7 @@ internal interface EvaluateStep {
}
private class EvaluateStepImpl(
private val context: Context,
private val tagInterpreter: TagInterpreter,
private val playlistInterpreter: PlaylistInterpreter,
private val storedPlaylists: StoredPlaylists,
@@ -57,6 +62,21 @@ private class EvaluateStepImpl(
}
builder
}
return libraryFactory.create(builder.build(), storedPlaylists, playlistInterpreter)
val graph = builder.build()
// Render graph to Graphviz in debug mode
if (BuildConfig.DEBUG) {
try {
val fileName = "music_graph_debug.dot"
graph.renderToGraphviz(context, fileName)
val filePath = context.filesDir.resolve(fileName).absolutePath
Log.d("EvaluateStep", "Music graph rendered to: $filePath")
Log.d("EvaluateStep", "To pull the file, run: adb pull $filePath")
} catch (e: Exception) {
Log.e("EvaluateStep", "Failed to render music graph", e)
}
}
return libraryFactory.create(graph, storedPlaylists, playlistInterpreter)
}
}
@@ -32,6 +32,7 @@ import org.oxycblt.musikr.covers.CoverResult
import org.oxycblt.musikr.fs.FS
import org.oxycblt.musikr.fs.File
import org.oxycblt.musikr.playlist.m3u.M3U
import org.oxycblt.musikr.util.map
import org.oxycblt.musikr.util.merge
import org.oxycblt.musikr.util.tryAsyncWith
@@ -54,39 +55,32 @@ private class ExploreStepImpl(private val fs: FS, private val storage: Storage)
val classified = Channel<Classified>(Channel.UNLIMITED)
val classifiedTask =
scope.tryAsyncWith(classified, Dispatchers.IO) {
for (file in files) {
if (file.mimeType.startsWith("audio/") || file.mimeType == M3U.MIME_TYPE) {
val cacheResult = storage.cache.read(file)
when (cacheResult) {
is CacheResult.Hit -> it.send(NeedsCover(cacheResult.song))
is CacheResult.Stale -> it.send(Finalized(NewSong(cacheResult.file)))
is CacheResult.Miss -> it.send(Finalized(NewSong(cacheResult.file)))
}
}
scope.map(files, classified, Dispatchers.IO) { file ->
if (!file.mimeType.startsWith("audio/") && file.mimeType != M3U.MIME_TYPE) {
return@map null
}
val cacheResult = storage.cache.read(file)
when (cacheResult) {
is CacheResult.Hit -> NeedsCover(cacheResult.song)
is CacheResult.Stale -> Finalized(NewSong(cacheResult.file))
is CacheResult.Miss -> Finalized(NewSong(cacheResult.file))
}
}
val finalized = Channel<Explored>(Channel.UNLIMITED)
val finalized = Channel<Finalized>(Channel.UNLIMITED)
val exploredTask =
scope.tryAsyncWith(finalized, Dispatchers.IO) {
for (item in classified) {
val result =
when (item) {
is Finalized -> item
is NeedsCover -> {
when (val coverResult =
item.cachedSong.coverId?.let { id ->
storage.covers.obtain(id)
}) {
is CoverResult.Hit ->
Finalized(item.cachedSong.toRawSong(coverResult.cover))
null -> Finalized(item.cachedSong.toRawSong(null))
else -> Finalized(NewSong(item.cachedSong.file))
}
}
scope.map(classified, finalized, Dispatchers.IO) { item ->
when (item) {
is Finalized -> item
is NeedsCover -> {
when (val coverResult =
item.cachedSong.coverId?.let { id -> storage.covers.obtain(id) }) {
is CoverResult.Hit ->
Finalized(item.cachedSong.toRawSong(coverResult.cover))
null -> Finalized(item.cachedSong.toRawSong(null))
else -> Finalized(NewSong(item.cachedSong.file))
}
it.send(result.explored)
}
}
}
val playlists = Channel<Explored>(Channel.UNLIMITED)
@@ -101,7 +95,7 @@ private class ExploreStepImpl(private val fs: FS, private val storage: Storage)
val mergeTask =
scope.tryAsyncWith(explored, Dispatchers.Main) {
for (item in finalized) {
it.send(item)
it.send(item.explored)
}
for (playlist in playlists) {
it.send(playlist)
@@ -32,9 +32,10 @@ import org.oxycblt.musikr.covers.MutableCovers
import org.oxycblt.musikr.metadata.Metadata
import org.oxycblt.musikr.metadata.MetadataExtractor
import org.oxycblt.musikr.tag.parse.TagParser
import org.oxycblt.musikr.util.map
import org.oxycblt.musikr.util.mapParallel
import org.oxycblt.musikr.util.merge
import org.oxycblt.musikr.util.tryAsyncWith
import org.oxycblt.musikr.util.tryParWith
internal interface ExtractStep {
suspend fun extract(
@@ -67,7 +68,7 @@ private class ExtractStepImpl(
val addingMs = System.currentTimeMillis()
val extract = Channel<ParsedExtractItem>(8)
val extractTask =
scope.tryParWith(8, explored, extract, Dispatchers.IO) { item ->
scope.mapParallel(8, explored, extract, Dispatchers.IO) { item ->
when (item) {
is RawSong -> Finalized(item)
is RawPlaylist -> Finalized(item)
@@ -80,37 +81,32 @@ private class ExtractStepImpl(
}
val parsed = Channel<ParsedCachingItem>(Channel.UNLIMITED)
val parsedTask =
scope.tryAsyncWith(parsed, Dispatchers.IO) {
for (item in extract) {
val result =
when (item) {
is Finalized -> item
is NeedsParsing -> {
val tags = tagParser.parse(item.metadata)
val cover =
when (val result =
covers.create(item.newSong.file, item.metadata)) {
is CoverResult.Hit -> result.cover
else -> null
}
NeedsCaching(
RawSong(
item.newSong.file,
item.metadata.properties,
tags,
cover,
// The thing about date added is that it's resolution can
// actually be expensive in some modes (ex. saf backend), so
// we resolve this by moving date added extraction as an
// extraction operation rather than doing the redundant work
// during exploration (well, kind of, MediaStore's date
// added query is basically free, it's only saf that has
// it's slow hacky workaround that we must accommodate
// here.)
item.newSong.file.addedMs.resolve() ?: addingMs))
scope.map(extract, parsed, Dispatchers.IO) { item ->
when (item) {
is Finalized -> item
is NeedsParsing -> {
val tags = tagParser.parse(item.metadata)
val cover =
when (val result = covers.create(item.newSong.file, item.metadata)) {
is CoverResult.Hit -> result.cover
else -> null
}
}
parsed.send(result)
NeedsCaching(
RawSong(
item.newSong.file,
item.metadata.properties,
tags,
cover,
// The thing about date added is that it's resolution can
// actually be expensive in some modes (ex. saf backend), so
// we resolve this by moving date added extraction as an
// extraction operation rather than doing the redundant work
// during exploration (well, kind of, MediaStore's date
// added query is basically free, it's only saf that has
// it's slow hacky workaround that we must accommodate
// here.)
item.newSong.file.addedMs.resolve() ?: addingMs))
}
}
}
val finalizedTask =
@@ -59,20 +59,35 @@ fun <T> CoroutineScope.tryAsyncWith(
}
}
fun <T, R> CoroutineScope.tryParWith(
n: Int,
channel: Channel<T>,
fun <T, R> CoroutineScope.map(
input: Channel<T>,
output: Channel<R>,
context: CoroutineContext = Dispatchers.Default,
block: suspend (T) -> R,
block: suspend (T) -> R?,
): Deferred<Result<Unit>> {
return tryAsync(context) {
for (item in input) {
block(item)?.let { output.send(it) }
}
output.close()
Unit
}
}
fun <T, R> CoroutineScope.mapParallel(
n: Int,
input: Channel<T>,
output: Channel<R>,
context: CoroutineContext = Dispatchers.Default,
block: suspend (T) -> R?,
): Deferred<Result<Unit>> {
return tryAsync(context) {
val deferreds = ArrayList<Deferred<Result<Unit>>>()
for (i in 0 until n) {
val deferred =
tryAsync(context) {
for (item in channel) {
output.send(block(item))
for (item in input) {
block(item)?.let { output.send(it) }
}
}
deferreds.add(deferred)