Every music file carries a small envelope of metadata. Title, artist, album, maybe a cover image. In theory it is tidy. In practice, one album can show up as Greatest Hits, greatest hits (with a trailing space) and GREATEST HITS in the same folder, and nobody agrees on how to write a collab credit.
The local library in Spotube has to show albums and artists for files that nobody on our side ever tagged. Nothing on disk says "this is an album". The app builds those groups itself, from whatever the tags happen to say. This post walks through how that works, and the places where we had to accept that the result is only as good as the tags.
Where the groups come from
The raw material is the local media index. LocalMediaCollectionsRepository sits on top of LocalMediaLibraryCoordinator and exposes three flows: the flat track list, the albums and the artists. All three are derived from the index and computed on Dispatchers.Default. Each one stays active for five seconds after its last collector leaves.
// modules/library/local/LocalMediaCollectionsRepository.kt (trimmed) class LocalMediaCollectionsRepository( coordinator: LocalMediaLibraryCoordinator ) { private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) val tracks: StateFlow<List<LocalMediaTrack>> = coordinator.cacheState .map { cache -> distinctLocalFiles(cache.folders.flatMap { it.tracks }) } .stateIn(scope, SharingStarted.WhileSubscribed(5_000), emptyList()) val albums: StateFlow<List<LocalMediaAlbum>> = tracks .map(::buildLocalAlbums) .stateIn(scope, SharingStarted.WhileSubscribed(5_000), emptyList()) val artists: StateFlow<List<LocalMediaArtist>> = tracks .map(::buildLocalArtists) .stateIn(scope, SharingStarted.WhileSubscribed(5_000), emptyList()) } View LocalMediaCollectionsRepository.kt on GitHub
The grouping itself lives in LocalMediaCollections.kt as plain functions, buildLocalAlbums and buildLocalArtists. They take a list and return a list, with no Android context, no Compose and no coroutines. That is why LocalMediaCollectionsTest can check the grouping rules on a plain JVM without a device.
One detail to know about: the same file can be visible through two URIs. On Android it can be a MediaStore URI and a Storage Access Framework document URI at the same time. distinctLocalFiles, which sits next to the repository in LocalMediaCollectionsRepository.kt, collapses those into one track and keeps every spelling in its aliases. indexByReferencePath maps each spelling back to that track, so a playlist that stores either URI still resolves.
Albums: one key, a lot of spellings
An album is any non-blank album tag. The grouping key is the trimmed, lowercased name. The first spelling we see becomes the display name.
// modules/library/local/LocalMediaCollections.kt (trimmed) fun buildLocalAlbums(tracks: List<LocalMediaTrack>): List<LocalMediaAlbum> { val byName = LinkedHashMap<String, Pair<String, MutableList<LocalMediaTrack>>>() tracks.forEach { track -> val displayName = track.album?.trim()?.takeIf { it.isNotBlank() } ?: return@forEach val key = normalizeGroupKey(displayName) byName.getOrPut(key) { displayName to mutableListOf() }.second.add(track) } return byName.map { (key, pair) -> val (displayName, groupTracks) = pair val sorted = groupTracks.sortedBy { it.name.trim().lowercase() } LocalMediaAlbum( key = key, name = displayName, tracks = sorted, coverBytes = sorted.firstNotNullOfOrNull { it.coverBytes?.takeIf { c -> c.isNotEmpty() } }) }.sortedBy { it.name.lowercase() } } View LocalMediaCollections.kt on GitHub
Blank album tags are skipped. Those tracks still show up in the flat track list, they just do not form an album. The test tracksAreGroupedByAlbumNameCaseInsensitively covers the three spellings from the intro, including the trailing-space one, and checks that the first casing wins.
Three spellings, one key, one album
There is a catch we want to be upfront about. The key is only the album tag. LocalTrackTags carries title, artists, album and a few numbers, but no album artist field feeds the key. So two unrelated records that are both called Greatest Hits end up as one album in the library. That is the trade-off for a grouping rule you can explain in one sentence. If your library looks odd, check the album tags first.
Artists: multi-credit tracks belong to everyone
Artist tags are the more interesting part. The native tag reader hands over all the credits of a track as one string, joined with "; ". LocalTrackTags.toTrack then splits that string on ;, trims each piece and drops the blanks. A track tagged A; B ends up with the artists ["A", "B"].
// modules/library/local/LocalMediaCollections.kt (trimmed) tracks.forEach { track -> val artists = track.artists.mapNotNull { it.trim().takeIf { name -> name.isNotBlank() } } if (artists.isEmpty()) return@forEach val distinct = artists.distinctBy { normalizeGroupKey(it) } distinct.forEach { artistName -> val key = normalizeGroupKey(artistName) byName.getOrPut(key) { artistName to mutableListOf() }.second.add(track) } } View LocalMediaCollections.kt on GitHub
Every credited artist gets the track. Across tracks, the casing merges for free because the key is the same. The test artistGroupsCoverEveryCreditedArtistWithoutDuplicates checks that case: one track credited to A and B, another credited to B and a, and a third credited to B alone. The artist A gets the first two tracks, and B gets all three.
Inside one track, distinctBy on the normalized key also collapses case-only repeats, so B and b in the same tag count as one credit. No test isolates that case yet, so read it as the current behavior rather than a guarantee.
Every credited artist gets the track
Artist track lists are also deduplicated by file path before sorting, so a single physical file cannot appear twice under the same artist.
Covers: first alphabetical track with art
Each album and artist needs one cover, and the rule is deliberately boring. Sort the group's tracks by name, then take the first track that has embedded art. Empty byte arrays count as "no art", so an empty image never wins the cover slot. emptyCoversAreTreatedAsMissing pins that down.
Picking the most common image would mean comparing bytes across every track in a group, and the answer would still shift with whatever happens to be indexed at the moment. Alphabetical order is predictable. You can read the test albumCoverComesFromTheFirstAlphabeticalTrackThatHasArt and know exactly which image will show up.
Navigation ids are just names
Albums and artists have no database id. The route is built from the normalized key: Routes.LocalAlbum(album.key) and Routes.LocalArtist(artist.key), the same stateless pattern as Routes.LocalFolder(path). When the screen opens, its view model collects albumFlow(key) or artistFlow(key). Those flows re-emit whenever the index changes and emit null while the album is not indexed, so an open screen follows the library instead of holding a stale copy. On null, the screen shows a not-found state.
Local playlists are one JSON document
Playlists that only reference on-device files are a different beast. They do not go in the index and they do not live on a server. LocalPlaylistRepository keeps the whole list as one JSON string under a single key inside a Preferences DataStore file, spotube_local_playlists.preferences_pb.
Each playlist is a small data class. Tracks are not copied in. A playlist only stores the paths, in the order the user picked them:
// modules/library/local/LocalPlaylistModels.kt (trimmed) @Serializable data class LocalPlaylist( val id: String, val name: String, val description: String? = null, val coverBase64: String? = null, val trackPaths: List<String> = emptyList(), val createdAtEpochMs: Long = 0) View LocalPlaylistModels.kt on GitHub
Ids start with local: so they can never collide with online playlist ids. A file that disappears is not removed from the playlist. The playlist view skips its path until the file is indexed again, and remapMovedTracks rewrites the stored paths when a move is detected.
Every write goes through one private function that reads the whole document, transforms it and writes it back inside a single edit block:
// modules/library/local/LocalPlaylistRepository.kt (trimmed) private suspend fun mutate(transform: (List<LocalPlaylist>) -> List<LocalPlaylist>) { store.edit { prefs -> val current = prefs[DatabaseKeys.LOCAL_PLAYLISTS_STATE_KEY]?.let { raw -> runCatching { json.decodeFromString<List<LocalPlaylist>>(raw) }.getOrNull() } ?: emptyList() val next = transform(current) prefs[DatabaseKeys.LOCAL_PLAYLISTS_STATE_KEY] = json.encodeToString(next) } } View LocalPlaylistRepository.kt on GitHub
Read, transform, encode, write: all inside one edit
Writing the whole document every time sounds wasteful, but a playlist library is a small amount of JSON. Keeping the read and the write in one edit means concurrent writers cannot lose each other's changes. The test movingAFileUpdatesEveryPlaylistWithoutDuplicatingAliases exercises the path rewrite. corruptedStoreFallsBackToEmpty checks the failure mode we care about most: a damaged file must never crash the library screen. When the flow reads a document it cannot decode, it emits an empty list, and the next successful edit rewrites the file.
Ids come from 16 random bytes, rendered as hex and prefixed with local:. Nothing clever, nothing that needs a server.
Covers for playlists take a different path. reencodeLocalCoverBase64 runs a picked image through encodeLocalCoverThumbnail, which downscales it to LOCAL_PLAYLIST_COVER_SIZE (480 px), and returns the result base64-encoded. That keeps a gallery photo from bloating the JSON document. If the picked image cannot be decoded, the cover is left unchanged. At the repository level, a null cover argument keeps the current cover and an empty string removes it. The edit form sends null when no new image was picked.
What we would tell ourselves earlier
Tags are a suggestion, not a contract. The grouping code is strict about what it normalizes (case, whitespace, blank tags) and deliberately does not guess beyond that: no album artist, no cover voting, no opinion on which spelling is right. Keeping the grouping pure is what makes that rule easy to test with a list of fake tracks.
If your library groups something wrong, the tag is usually the culprit, and the fastest way to help us is a small example of the tags involved. Open an issue on the Spotube GitHub repository with the spellings you see, and we will take it from there.
References
- MusicBrainz artist credits style guide: how multi-artist credits are written in a large open music database.
- ID3 on Wikipedia: the common tag format that holds title, artist, album and cover art in audio files.
- Dispatchers.Default: the coroutine dispatcher used for CPU-bound work.
- StateFlow: the state holder flow type behind the tracks, albums and artists lists.
- MediaStore: Android's shared media index.
- Storage Access Framework: Android document URIs, the second way a file can be addressed.
- Jetpack DataStore: the Preferences DataStore used for local playlists.
- Base64 on Wikipedia: the encoding used for playlist cover thumbnails.
Originally published on spotube.org.


