musikr: hard revert to pre-filetreecache system

This commit is contained in:
Alexander Capehart
2025-06-16 07:23:55 -06:00
parent 5f303b1be1
commit b3acb31008
43 changed files with 318 additions and 1864 deletions
-135
View File
@@ -1,135 +0,0 @@
# Musikr Architecture
## Overview
Musikr is a highly opinionated multithreaded music loader that provides advanced music functionality for Auxio. It bypasses Android's MediaStore to directly access music files using the Storage Access Framework (SAF) and [TagLib](https://taglib.org/) for metadata extraction.
## Core Components
### Pipeline Architecture
Musikr uses a three-stage pipeline for music indexing:
1. **Explore Step** - Discovers music files on the device
2. **Extract Step** - Extracts metadata from discovered files
3. **Evaluate Step** - Processes extracted data to build the music library
```mermaid
graph LR
A[Music Locations] --> B[Explore Step]
B --> C[Extract Step]
C --> D[Evaluate Step]
D --> E[Library]
subgraph Pipeline
B
C
D
end
```
### Key Interfaces
- **Musikr** - Main entry point for the library
- **Storage** - Manages persistent storage needs
- **Library** - Represents the loaded music collection
- **MutableLibrary** - Modifiable version of the library
## Module Structure
### 1. File System (`fs` package)
- **Location.Opened** - Represents a location to search for music
- **DeviceFS** - Provides access to device storage
- **FileTreeCache** - Caches filesystem structure for faster indexing
### 2. Pipeline (`pipeline` package)
- **ExploreStep** - Discovers music files on the device
- **ExtractStep** - Extracts metadata from discovered files
- **EvaluateStep** - Processes extracted data to build the library
- **PipelineItem** - Data items flowing through the pipeline
### 3. Metadata (`metadata` package)
- **Metadata** - Extracted file metadata
- **MetadataExtractor** - Extracts metadata using TagLib
- **TagLibJNI** - JNI bridge to native TagLib library
### 4. Tag Processing (`tag` package)
- **TagParser** - Parses raw tag data into structured format
- **TagInterpreter** - Interprets tags based on user preferences
- **ParsedTags** - Represents parsed metadata tags
### 5. Model (`model` package)
- **LibraryImpl** - Implementation of the music library
- **SongImpl**, **AlbumImpl**, **ArtistImpl**, **GenreImpl** - Music entity implementations
- **LibraryFactory** - Creates library instances from pipeline data
### 6. Covers (`covers` package)
- **Covers** - Interface for album cover management
- **EmbeddedCovers** - Extracts covers embedded in music files
- **FSCovers** - Discovers cover art in the filesystem
- **StoredCovers** - Manages persistent storage of covers
### 7. Cache (`cache` package)
- **Cache** - Caches processed music data
- **DBCache** - Database implementation of caching
### 8. Playlist (`playlist` package)
- **PlaylistFile** - Represents a playlist file
- **ExternalPlaylistManager** - Manages external playlist files
- **PlaylistInterpreter** - Interprets playlist formats
## Native Component
Musikr includes a native component built with TagLib for fast and accurate metadata extraction:
```mermaid
graph TD
A[TagLibJNI] --> B[JNI Bridge]
B --> C[TagLib Library]
C --> D[Music File Metadata]
```
### Native Files (`cpp` directory)
- **taglib_jni.cpp** - Main JNI implementation
- **JMetadataBuilder** - Builds metadata objects from TagLib
- **JTagMap** - Maps between Java and C++ tag structures
- **JInputStream** - Input stream adapter for TagLib
## Data Flow
```mermaid
sequenceDiagram
participant User
participant Musikr
participant ExploreStep
participant ExtractStep
participant EvaluateStep
participant Storage
User->>Musikr: run(locations)
Musikr->>ExploreStep: explore(locations)
ExploreStep->>Storage: Read cache
ExploreStep-->>Musikr: Explored files
Musikr->>ExtractStep: extract(explored)
ExtractStep->>TagLibJNI: Extract metadata
ExtractStep-->>Musikr: Extracted metadata
Musikr->>EvaluateStep: evaluate(extracted)
EvaluateStep->>Storage: Store processed data
EvaluateStep-->>Musikr: Library
Musikr-->>User: LibraryResult
```
## Threading Model
Musikr uses Kotlin Coroutines for concurrent processing:
- Pipeline stages use `flatMapMerge` and `distributedMap` for parallel processing
- Bounded buffer channels manage backpressure
- IO operations are dispatched to `Dispatchers.IO`
## Best Practices for Extension
1. The API is minimized and unstable - be prepared to fork and modify
2. No defaults are provided - carefully consider parameter choices
3. Musikr is stateless except for Storage - manage long-term state yourself
4. When adding functionality, follow the pipeline architecture pattern
-3
View File
@@ -4,7 +4,6 @@ plugins {
id 'com.android.library'
id 'org.jetbrains.kotlin.android'
id "com.google.devtools.ksp"
id "org.jetbrains.kotlin.plugin.serialization"
id "com.diffplug.spotless"
id "kotlin-parcelize"
id "org.jetbrains.dokka"
@@ -63,8 +62,6 @@ dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$kotlin_coroutines_version"
implementation 'org.jetbrains.kotlinx:kotlinx-serialization-json:1.8.0'
// AndroidX
implementation "androidx.core:core-ktx:$core_version"
-90
View File
@@ -1,90 +0,0 @@
# Native Code (C++) Component
## Overview
This directory contains the native C++ code that bridges between Java and TagLib. It enables fast and accurate metadata extraction from music files.
## Key Components
### JNI Implementation
**taglib_jni.cpp**
- Main JNI implementation
- Registers native methods
- Handles JNI environment setup
**JMetadataBuilder**
- Builds metadata objects from TagLib
- Extracts tags and properties
- Maps between TagLib and Java structures
**JTagMap**
- Maps between Java and C++ tag structures
- Provides bidirectional conversion
**JInputStream**
- Input stream adapter for TagLib
- Bridges between Java I/O and TagLib I/O
### Utility Classes
**JStringRef**
- Manages JNI string references
- Handles UTF conversions
**JByteArrayRef**
- Manages JNI byte array references
- Provides safe access to Java byte arrays
**JObjectRef**
- Manages JNI object references
- Provides RAII-style resource management
**JClassRef**
- Manages JNI class references
- Caches class and method lookups
**util.h**
- Utility functions for JNI
- Error handling and logging
### Build Configuration
**CMakeLists.txt**
- CMake build configuration
- Configures TagLib integration
**build_taglib.sh**
- Script to build TagLib from source
- Configures platform-specific options
**android.toolchain.cmake**
- Android-specific CMake toolchain
## TagLib Integration
TagLib is included as a subproject and built from source. The `taglib` directory contains the TagLib source code, which is a powerful and feature-rich library for reading and writing audio metadata.
## Build Process
1. The build starts with `build_taglib.sh`
2. TagLib is configured and built with CMake
3. The JNI wrapper is built against TagLib
4. The resulting library is packaged into the AAR
## JNI Interface
The native methods are exposed through `TagLibJNI.kt` in the Java code. The main functionalities include:
- Reading metadata from audio files
- Extracting embedded cover art
- Accessing audio properties (bitrate, sample rate, etc.)
## Extension Points
When extending the native code:
1. For new tag formats, update the TagLib integration
2. For new metadata fields, add them to JMetadataBuilder
3. For performance improvements, optimize the JNI bridge
4. For platform-specific optimizations, update the build configuration
@@ -21,15 +21,10 @@ package org.oxycblt.musikr
import org.oxycblt.musikr.cache.MutableCache
import org.oxycblt.musikr.covers.Cover
import org.oxycblt.musikr.covers.MutableCovers
import org.oxycblt.musikr.fs.Location
import org.oxycblt.musikr.fs.Location.Opened
import org.oxycblt.musikr.fs.device.FileTreeCache
import org.oxycblt.musikr.playlist.db.StoredPlaylists
import org.oxycblt.musikr.tag.interpret.Naming
import org.oxycblt.musikr.tag.interpret.Separators
data class Query(val source: List<Location.Opened>, val exclude: List<Location>)
/** Side-effect laden [Storage] for use during music loading and [MutableLibrary] operation. */
data class Storage(
/**
@@ -50,10 +45,7 @@ data class Storage(
* be used during music loading and mutated when creating, renaming, or deleting playlists in
* the library.
*/
val storedPlaylists: StoredPlaylists,
/** A cache for file tree information to optimize file system exploration. */
val fileTreeCache: FileTreeCache
val storedPlaylists: StoredPlaylists
)
/** Configuration for how to interpret and extrapolate certain audio tags. */
@@ -19,13 +19,13 @@
package org.oxycblt.musikr
import android.content.Context
import android.util.Log
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.buffer
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.onStart
import org.oxycblt.musikr.fs.MusicLocation
import org.oxycblt.musikr.pipeline.EvaluateStep
import org.oxycblt.musikr.pipeline.ExploreStep
import org.oxycblt.musikr.pipeline.ExtractStep
@@ -47,13 +47,13 @@ interface Musikr {
/**
* Start loading music from the given [locations] and the configuration provided earlier.
*
* @param query The [Query] to load music from.
* @param locations The [MusicLocation]s to search for music in.
* @param onProgress Optional callback to receive progress on the current status of the music
* pipeline. Warning: These events will be rapid-fire.
* @return A handle to the newly created library alongside further cleanup.
*/
suspend fun run(
query: Query,
locations: List<MusicLocation>,
onProgress: suspend (IndexingProgress) -> Unit = {}
): LibraryResult
@@ -70,7 +70,6 @@ interface Musikr {
*/
fun new(context: Context, storage: Storage, interpretation: Interpretation): Musikr =
MusikrImpl(
context,
storage,
ExploreStep.from(context, storage, interpretation),
ExtractStep.from(context, storage),
@@ -97,7 +96,7 @@ sealed interface IndexingProgress {
/**
* Currently indexing and extracting tags from device music.
*
* @param explored The amount of music currently found from the given [Query].
* @param explored The amount of music currently found from the given [MusicLocation]s.
* @param loaded The amount of music that has had metadata extracted and parsed.
*/
data class Songs(val loaded: Int, val explored: Int) : IndexingProgress
@@ -111,35 +110,32 @@ sealed interface IndexingProgress {
}
private class MusikrImpl(
private val context: Context,
private val storage: Storage,
private val exploreStep: ExploreStep,
private val extractStep: ExtractStep,
private val evaluateStep: EvaluateStep
) : Musikr {
override suspend fun run(query: Query, onProgress: suspend (IndexingProgress) -> Unit) =
coroutineScope {
val start = System.currentTimeMillis()
var exploredCount = 0
var extractedCount = 0
val explored =
exploreStep
.explore(query)
.buffer(Channel.UNLIMITED)
.onStart { onProgress(IndexingProgress.Songs(0, 0)) }
.onEach { onProgress(IndexingProgress.Songs(extractedCount, ++exploredCount)) }
val extracted =
extractStep
.extract(explored)
.buffer(Channel.UNLIMITED)
.onEach { onProgress(IndexingProgress.Songs(++extractedCount, exploredCount)) }
.onCompletion { onProgress(IndexingProgress.Indeterminate) }
val library = evaluateStep.evaluate(extracted)
Log.d(
"Musikr",
"Loaded ${library.songs.size} songs in ${System.currentTimeMillis() - start}ms")
LibraryResultImpl(storage, library)
}
override suspend fun run(
locations: List<MusicLocation>,
onProgress: suspend (IndexingProgress) -> Unit
) = coroutineScope {
var exploredCount = 0
var extractedCount = 0
val explored =
exploreStep
.explore(locations)
.buffer(Channel.UNLIMITED)
.onStart { onProgress(IndexingProgress.Songs(0, 0)) }
.onEach { onProgress(IndexingProgress.Songs(extractedCount, ++exploredCount)) }
val extracted =
extractStep
.extract(explored)
.buffer(Channel.UNLIMITED)
.onEach { onProgress(IndexingProgress.Songs(++extractedCount, exploredCount)) }
.onCompletion { onProgress(IndexingProgress.Indeterminate) }
val library = evaluateStep.evaluate(extracted)
LibraryResultImpl(storage, library)
}
}
private class LibraryResultImpl(
@@ -55,8 +55,6 @@ internal abstract class CacheDatabase : RoomDatabase() {
internal interface CacheReadDao {
@Query("SELECT * FROM CachedSongData WHERE uri = :uri")
suspend fun selectSong(uri: String): CachedSongData?
@Query("SELECT * FROM CachedSongData") suspend fun selectAllSongs(): List<CachedSongData>
}
@Dao
+1 -15
View File
@@ -19,8 +19,6 @@
package org.oxycblt.musikr.cache.db
import android.content.Context
import android.net.Uri
import kotlinx.coroutines.sync.Mutex
import org.oxycblt.musikr.cache.Cache
import org.oxycblt.musikr.cache.CacheResult
import org.oxycblt.musikr.cache.CachedSong
@@ -35,20 +33,8 @@ import org.oxycblt.musikr.tag.parse.ParsedTags
* Create an instance with [from].
*/
class DBCache private constructor(private val readDao: CacheReadDao) : Cache {
@Volatile private var mapping: MutableMap<Uri, CachedSongData>? = null
private var mappingLock = Mutex()
override suspend fun read(file: DeviceFile): CacheResult {
mappingLock.lock()
val mapping =
this.mapping
?: readDao
.selectAllSongs()
.associateBy { it.uri }
.toMutableMap()
.also { mapping = it }
mappingLock.unlock()
val dbSong = mapping[file.uri] ?: return CacheResult.Miss(file)
val dbSong = readDao.selectSong(file.uri.toString()) ?: return CacheResult.Miss(file)
if (dbSong.modifiedMs != file.modifiedMs) {
return CacheResult.Stale(file, dbSong.addedMs)
}
@@ -1,74 +0,0 @@
# Covers Package
## Overview
The covers package provides functionality for discovering, extracting, and managing album cover art. It handles embedded covers in music files, external cover images, and persistent storage.
## Key Components
### Core Interfaces
**Covers** (`Covers.kt`)
- Generic interface for cover art management
- Provides methods to obtain and manage covers
**Cover** (`Covers.kt`)
- Represents a cover image
- Contains cover metadata and access methods
### Cover Sources
**EmbeddedCovers** (`embedded/EmbeddedCovers.kt`)
- Extracts covers embedded in music files
- Uses metadata extraction to access embedded images
**FSCovers** (`fs/FSCovers.kt`)
- Discovers cover art in the filesystem
- Searches for common cover image filenames
**ChainedCovers** (`chained/ChainedCovers.kt`)
- Combines multiple cover sources
- Provides fallback mechanisms
### Storage
**StoredCovers** (`stored/StoredCovers.kt`)
- Manages persistent storage of covers
- Handles caching and retrieval
**CoverStorage** (`stored/CoverStorage.kt`)
- Low-level cover storage operations
- Manages the cover storage directory
**Transcoding** (`stored/Transcoding.kt`)
- Handles image format conversion
- Optimizes covers for storage and display
### Identification
**CoverIdentifier** (`embedded/CoverIdentifier.kt`)
- Generates unique identifiers for covers
- Used for caching and referencing
## Cover Flow
1. During music indexing, covers are extracted or discovered
2. Covers are identified and stored
3. Songs reference covers by identifier
4. When needed, covers are retrieved from storage
## Key Features
- **Multiple sources** - Embedded, filesystem, and custom sources
- **Efficient storage** - Avoids duplicates through identification
- **Format optimization** - Transcodes images for optimal storage
- **Lazy loading** - Loads covers only when needed
## Extension Points
When extending the cover functionality:
1. For new cover sources, implement the Covers interface
2. For custom storage, extend or replace StoredCovers
3. For format-specific handling, update the Transcoding class
4. For performance improvements, optimize the identification and storage mechanisms
@@ -25,9 +25,6 @@ import android.os.ParcelFileDescriptor
import androidx.core.net.toUri
import java.io.InputStream
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.filterIsInstance
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.withContext
import org.oxycblt.musikr.covers.Cover
import org.oxycblt.musikr.covers.CoverResult
@@ -99,12 +96,11 @@ class MutableFSCovers(private val context: Context) : MutableCovers<FDCover> {
override suspend fun create(file: DeviceFile, metadata: Metadata): CoverResult<FDCover> {
// Since DeviceFiles is a streaming API, we have to wait for the current recursive
// query to finally finish to be able to have a complete list of siblings to search for.
val parent = file.parent
val parent = file.parent.await()
val bestCover =
parent.children
.filterIsInstance<DeviceFile>()
.map { it to coverArtScore(it) }
.toList()
.maxBy { it.second }
if (bestCover.second > 0) {
return CoverResult.Hit(FolderCoverImpl(context, bestCover.first.uri))
@@ -132,7 +128,7 @@ class MutableFSCovers(private val context: Context) : MutableCovers<FDCover> {
// See if the name contains any of the preferred cover names. This helps weed out
// images that are not actually cover art and are just there.,
var score =
(preferredCoverNames + requireNotNull(file.parent.path.name))
(preferredCoverNames + requireNotNull(file.parent.await().path.name))
.withIndex()
.filter { name.contains(it.value, ignoreCase = true) }
.sumOf { it.index + 1 }
@@ -1,76 +0,0 @@
/*
* Copyright (c) 2024 Auxio Project
* Location.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.fs
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.DocumentsContract
import org.oxycblt.musikr.fs.device.contentResolverSafe
import org.oxycblt.musikr.fs.path.DocumentPathFactory
sealed class Location(val uri: Uri, val path: Path) {
override fun equals(other: Any?) = other is Location && uri == other.uri
override fun hashCode() = 31 * uri.hashCode()
override fun toString(): String = uri.toString()
class Unopened private constructor(uri: Uri, path: Path) : Location(uri, path) {
fun open(context: Context): Opened? {
if (isUnopened(context, uri)) {
try {
context.contentResolverSafe.takePersistableUriPermission(
uri,
Intent.FLAG_GRANT_READ_URI_PERMISSION or
Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
} catch (e: Exception) {
// Not fully sure what happens if I'm disallowed to take the permission,
// check for both circumstances (error or no-op)
return null
}
if (isUnopened(context, uri)) {
return null
}
}
return Opened(uri, path)
}
private fun isUnopened(context: Context, uri: Uri) =
context.contentResolverSafe.persistedUriPermissions.none {
it.uri == uri && it.isReadPermission && it.isWritePermission
}
companion object {
fun from(context: Context, uri: Uri): Unopened? {
if (!DocumentsContract.isTreeUri(uri)) return null
val documentPathFactory = DocumentPathFactory.from(context)
val path = documentPathFactory.unpackDocumentTreeUri(uri) ?: return null
return Unopened(uri, path)
}
}
}
class Opened internal constructor(uri: Uri, path: Path) : Location(uri, path) {
override fun equals(other: Any?) = other is Opened && uri == other.uri && path == other.path
override fun hashCode() = 31 * uri.hashCode() + path.hashCode()
}
}
@@ -0,0 +1,72 @@
/*
* Copyright (c) 2024 Auxio Project
* MusicLocation.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.fs
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.DocumentsContract
import org.oxycblt.musikr.fs.device.contentResolverSafe
import org.oxycblt.musikr.fs.path.DocumentPathFactory
import org.oxycblt.musikr.util.splitEscaped
class MusicLocation private constructor(val uri: Uri, val path: Path) {
override fun equals(other: Any?) = other is MusicLocation && uri == other.uri
override fun hashCode() = 31 * uri.hashCode()
override fun toString(): String = uri.toString()
companion object {
fun new(context: Context, uri: Uri): MusicLocation? {
if (!DocumentsContract.isTreeUri(uri)) return null
val documentPathFactory = DocumentPathFactory.from(context)
val path = documentPathFactory.unpackDocumentTreeUri(uri) ?: return null
val notPersisted =
context.contentResolverSafe.persistedUriPermissions.none {
it.uri == uri && it.isReadPermission && it.isWritePermission
}
if (notPersisted) {
context.contentResolverSafe.takePersistableUriPermission(
uri,
Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
}
return MusicLocation(uri, path)
}
fun existing(context: Context, uri: Uri): MusicLocation? {
val documentPathFactory = DocumentPathFactory.from(context)
if (!DocumentsContract.isTreeUri(uri)) return null
val notPersisted =
context.contentResolverSafe.persistedUriPermissions.none {
it.uri == uri && it.isReadPermission && it.isWritePermission
}
if (notPersisted) return null
val path = documentPathFactory.unpackDocumentTreeUri(uri) ?: return null
return MusicLocation(uri, path)
}
fun toString(list: List<MusicLocation>) =
list.joinToString(";") { it.uri.toString().replace(";", "\\;") }
fun existing(context: Context, string: String): List<MusicLocation> {
return string.splitEscaped { it == ';' }.mapNotNull { existing(context, Uri.parse(it)) }
}
}
}
@@ -1,72 +0,0 @@
# Filesystem Package
## Overview
The filesystem package provides abstraction layers for accessing music files on Android devices. It handles the complexities of the Storage Access Framework (SAF) and provides efficient caching mechanisms.
## Key Components
### Core Types
**Location.Opened** (`Location.Opened.kt`)
- Represents a location to search for music
- Can be a device storage location or content URI
**Path** (`Path.kt`)
- Abstract representation of a file path
- Handles both traditional file paths and content URIs
**Format** (`Format.kt`)
- Represents file formats and their properties
- Maps MIME types to file extensions
### Device Access
**DeviceFS** (`DeviceFS.kt`)
- Provides access to device storage
- Handles SAF permissions and access
- Performs filesystem traversal
**DeviceFSEntries** (`DeviceFSEntries.kt`)
- Represents filesystem entries (files and directories)
- Provides metadata about filesystem items
**DeviceFile** (in `DeviceFSEntries.kt`)
- Represents a music file on the device
- Contains file metadata needed for processing
### Caching
**FileTreeCache** (`FileTreeCache.kt`)
- Caches filesystem structure for faster indexing
- Provides incremental updates to avoid full rescans
### Path Interpretation
**Path Package** (`path/` directory)
- **DocumentPathFactory** - Creates paths from document URIs
- **MediaStorePathInterpreter** - Interprets MediaStore paths
- **VolumeManager** - Manages storage volumes
## Usage Flow
1. User provides `Location.Opened`s to scan
2. `DeviceFS` traverses these locations
3. `FileTreeCache` optimizes subsequent scans
4. Discovered files are passed to the pipeline for processing
## Key Features
- **Storage Access Framework** integration for modern Android storage access
- **Incremental scanning** to minimize resource usage
- **Path abstraction** to handle different Android storage mechanisms
- **Volume mapping** to resolve relative paths
## Extension Points
When extending the filesystem functionality:
1. For new storage types, implement appropriate Path implementations
2. For performance improvements, consider optimizing the FileTreeCache
3. For new file formats, update the Format class
4. For custom traversal strategies, extend DeviceFS
@@ -22,33 +22,20 @@ import android.content.ContentResolver
import android.content.Context
import android.net.Uri
import android.provider.DocumentsContract
import android.util.Log
import androidx.core.net.toUri
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.emitAll
import kotlinx.coroutines.flow.emptyFlow
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.flatMapMerge
import kotlinx.coroutines.flow.flattenMerge
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.mapNotNull
import kotlinx.coroutines.flow.merge
import kotlinx.coroutines.flow.shareIn
import kotlinx.coroutines.flow.takeWhile
import kotlinx.coroutines.flow.transform
import org.oxycblt.musikr.Query
import org.oxycblt.musikr.fs.Location
import org.oxycblt.musikr.fs.Location.Opened
import org.oxycblt.musikr.fs.MusicLocation
import org.oxycblt.musikr.fs.Path
internal interface DeviceFS {
fun explore(query: Query, fileTree: FileTree): Flow<DeviceDirectory>
fun explore(locations: Flow<MusicLocation>): Flow<DeviceFile>
companion object {
fun from(context: Context, withHidden: Boolean): DeviceFS =
@@ -56,246 +43,80 @@ internal interface DeviceFS {
}
}
@OptIn(ExperimentalCoroutinesApi::class)
private class DeviceFSImpl(
private val contentResolver: ContentResolver,
private val withHidden: Boolean
) : DeviceFS {
private val explorationScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
override fun explore(query: Query, fileTree: FileTree) =
query.source.asFlow().mapNotNull { location ->
queryRoot(location, fileTree, query.exclude)
override fun explore(locations: Flow<MusicLocation>): Flow<DeviceFile> =
locations.flatMapMerge { location ->
exploreDirectoryImpl(
location.uri,
DocumentsContract.getTreeDocumentId(location.uri),
location.path,
null)
}
private suspend fun queryRoot(
location: Location.Opened,
fileTree: FileTree,
exclude: List<Location>
): DeviceDirectory? {
val treeDocumentId = DocumentsContract.getTreeDocumentId(location.uri)
val uri = DocumentsContract.buildDocumentUriUsingTree(location.uri, treeDocumentId)
val modifiedMs =
contentResolver.useQuery(
uri, arrayOf(DocumentsContract.Document.COLUMN_LAST_MODIFIED)) { cursor ->
if (!cursor.moveToFirst()) return@useQuery null
val lastModifiedIndex =
cursor.getColumnIndexOrThrow(
DocumentsContract.Document.COLUMN_LAST_MODIFIED)
cursor.getLong(lastModifiedIndex)
}
if (modifiedMs == null) {
return null
}
return query(
location.uri, treeDocumentId, location.path, modifiedMs, null, fileTree, exclude)
}
private suspend fun query(
private fun exploreDirectoryImpl(
rootUri: Uri,
treeDocumentId: String,
path: Path,
modifiedMs: Long,
parent: DeviceDirectory?,
fileTree: FileTree,
exclude: List<Location>
): DeviceDirectory = coroutineScope {
val uri = DocumentsContract.buildDocumentUriUsingTree(rootUri, treeDocumentId)
val cached = fileTree.queryDirectory(uri)
if (cached != null && cached.modifiedMs == modifiedMs) {
return@coroutineScope hydrateCached(
cached = cached, parentDir = parent, path = path, fileTree = fileTree, exclude)
relativePath: Path,
parent: Deferred<DeviceDirectory>?
): Flow<DeviceFile> = flow {
// Make a kotlin future
val uri = DocumentsContract.buildChildDocumentsUriUsingTree(rootUri, treeDocumentId)
val directoryDeferred = CompletableDeferred<DeviceDirectory>()
val recursive = mutableListOf<Flow<DeviceFile>>()
val children = mutableListOf<DeviceFSEntry>()
contentResolver.useQuery(uri, PROJECTION) { cursor ->
val childUriIndex =
cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DOCUMENT_ID)
val displayNameIndex =
cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DISPLAY_NAME)
val mimeTypeIndex =
cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_MIME_TYPE)
val sizeIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_SIZE)
val lastModifiedIndex =
cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED)
while (cursor.moveToNext()) {
val childId = cursor.getString(childUriIndex)
val displayName = cursor.getString(displayNameIndex)
// Skip hidden files/directories if ignoreHidden is true
if (!withHidden && displayName.startsWith(".")) {
continue
}
val newPath = relativePath.file(displayName)
val mimeType = cursor.getString(mimeTypeIndex)
val lastModified = cursor.getLong(lastModifiedIndex)
if (mimeType == DocumentsContract.Document.MIME_TYPE_DIR) {
recursive.add(
exploreDirectoryImpl(rootUri, childId, newPath, directoryDeferred))
} else {
val size = cursor.getLong(sizeIndex)
val childUri = DocumentsContract.buildDocumentUriUsingTree(rootUri, childId)
val file =
DeviceFile(
uri = childUri,
mimeType = mimeType,
path = newPath,
size = size,
modifiedMs = lastModified,
parent = directoryDeferred)
children.add(file)
emit(file)
}
}
directoryDeferred.complete(DeviceDirectory(uri, relativePath, parent, children))
emitAll(recursive.asFlow().flattenMerge())
}
val dir =
DeviceDirectoryImpl(
uri = uri,
path = path,
modifiedMs = modifiedMs,
parent = parent,
children = emptyFlow())
dir.children =
flow {
Log.d("DeviceFS", "Querying $uri")
contentResolver.useQuery(
DocumentsContract.buildChildDocumentsUriUsingTree(
rootUri,
treeDocumentId,
),
projection = PROJECTION,
sortOrder = "${DocumentsContract.Document.COLUMN_DISPLAY_NAME} DESC") {
cursor ->
val childUriIndex =
cursor.getColumnIndexOrThrow(
DocumentsContract.Document.COLUMN_DOCUMENT_ID)
val displayNameIndex =
cursor.getColumnIndexOrThrow(
DocumentsContract.Document.COLUMN_DISPLAY_NAME)
val mimeTypeIndex =
cursor.getColumnIndexOrThrow(
DocumentsContract.Document.COLUMN_MIME_TYPE)
val sizeIndex =
cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_SIZE)
val lastModifiedIndex =
cursor.getColumnIndexOrThrow(
DocumentsContract.Document.COLUMN_LAST_MODIFIED)
val childSubdirUris = mutableListOf<String>()
val childFileUris = mutableListOf<String>()
val subqueries = mutableListOf<DeviceDirectory>()
while (cursor.moveToNext()) {
val childId = cursor.getString(childUriIndex)
val displayName = cursor.getString(displayNameIndex)
// Skip hidden files/directories if ignoreHidden is true
if (!withHidden && displayName.startsWith(".")) {
continue
}
val newPath = path.file(displayName)
val mimeType = cursor.getString(mimeTypeIndex)
val lastModified = cursor.getLong(lastModifiedIndex)
if (mimeType == DocumentsContract.Document.MIME_TYPE_DIR) {
// Check if this directory should be excluded
val shouldExclude =
exclude.any { excluded ->
// Check if the current path matches the excluded path
// exactly
excluded.path.volume == newPath.volume &&
excluded.path.components == newPath.components
}
if (shouldExclude) {
continue
}
val subdir =
query(
rootUri = rootUri,
treeDocumentId = childId,
path = newPath,
modifiedMs = modifiedMs,
parent = dir,
fileTree = fileTree,
exclude = exclude)
childSubdirUris.add(subdir.uri.toString())
emit(StreamedFile.More(subdir))
} else {
Log.d("DeviceFS", "Querying file $childId")
val size = cursor.getLong(sizeIndex)
val childUri =
DocumentsContract.buildDocumentUriUsingTree(
rootUri, childId)
val file =
DeviceFile(
uri = childUri,
mimeType = mimeType,
path = newPath,
size = size,
modifiedMs = lastModified,
parent = dir)
val write =
CachedFile(
uri = childUri.toString(),
name = displayName,
modifiedMs = lastModified,
mimeType = mimeType,
size = size)
fileTree.updateFile(childUri, write)
childFileUris.add(childUri.toString())
emit(StreamedFile.More(file))
}
}
val writeDir =
CachedDirectory(
uri = uri.toString(),
name = requireNotNull(path.name),
modifiedMs = modifiedMs,
subdirUris = childSubdirUris,
fileUris = childFileUris)
fileTree.updateDirectory(uri, writeDir)
emit(StreamedFile.Done)
}
}
.shareIn(explorationScope, SharingStarted.Lazily, replay = Int.MAX_VALUE)
.takeWhile { it is StreamedFile.More }
.map { (it as StreamedFile.More).value }
dir
}
private suspend fun hydrateCached(
cached: CachedDirectory,
parentDir: DeviceDirectory?,
path: Path,
fileTree: FileTree,
exclude: List<Location>
): DeviceDirectory = coroutineScope {
val dir =
DeviceDirectoryImpl(
uri = cached.uri.toUri(),
path = path,
modifiedMs = cached.modifiedMs,
parent = parentDir,
children = emptyFlow())
dir.children =
flow {
emitAll(
merge(
cached.subdirUris
.asFlow()
.transform { subdirUriString ->
val subdirUri = subdirUriString.toUri()
val cachedSubdir =
requireNotNull(fileTree.queryDirectory(subdirUri)) {
"No cached subdir for $subdirUri, malformed cache! Rescan needed."
}
val subdirPath = dir.path.file(cachedSubdir.name)
val shouldExclude =
exclude.any { excluded ->
excluded.path.volume == subdirPath.volume &&
excluded.path.components ==
subdirPath.components
}
if (shouldExclude) {
return@transform
}
emit(
hydrateCached(
cachedSubdir, dir, subdirPath, fileTree, exclude))
}
.filterNotNull(),
cached.fileUris.asFlow().map {
val cachedFile = requireNotNull(fileTree.queryFile(it.toUri()))
DeviceFile(
uri = it.toUri(),
path = dir.path.file(cachedFile.name),
modifiedMs = cachedFile.modifiedMs,
mimeType = cachedFile.mimeType,
size = cachedFile.size,
parent = dir)
})
.map { StreamedFile.More(it) })
emit(StreamedFile.Done)
}
.flowOn(Dispatchers.IO)
.shareIn(explorationScope, SharingStarted.Lazily, replay = Int.MAX_VALUE)
.takeWhile { it is StreamedFile.More }
.map { (it as StreamedFile.More).value }
dir
}
private sealed interface StreamedFile {
data class More(val value: DeviceFSEntry) : StreamedFile
data object Done : StreamedFile
}
private companion object {
private val PROJECTION =
val PROJECTION =
arrayOf(
DocumentsContract.Document.COLUMN_DOCUMENT_ID,
DocumentsContract.Document.COLUMN_DISPLAY_NAME,
@@ -304,11 +125,3 @@ private class DeviceFSImpl(
DocumentsContract.Document.COLUMN_LAST_MODIFIED)
}
}
private class DeviceDirectoryImpl(
override val uri: Uri,
override val path: Path,
override val modifiedMs: Long,
override val parent: DeviceDirectory?,
override var children: Flow<DeviceFSEntry>,
) : DeviceDirectory
@@ -19,35 +19,26 @@
package org.oxycblt.musikr.fs.device
import android.net.Uri
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.emitAll
import kotlinx.coroutines.flow.transform
import kotlinx.coroutines.Deferred
import org.oxycblt.musikr.fs.Path
sealed interface DeviceFSEntry {
val uri: Uri
val path: Path
val modifiedMs: Long
}
interface DeviceDirectory : DeviceFSEntry {
val parent: DeviceDirectory?
val children: Flow<DeviceFSEntry>
}
data class DeviceDirectory(
override val uri: Uri,
override val path: Path,
val parent: Deferred<DeviceDirectory>?,
var children: List<DeviceFSEntry>
) : DeviceFSEntry
data class DeviceFile(
override val uri: Uri,
override val path: Path,
override val modifiedMs: Long,
val modifiedMs: Long,
val mimeType: String,
val size: Long,
val parent: DeviceDirectory
val parent: Deferred<DeviceDirectory>
) : DeviceFSEntry
fun DeviceDirectory.flatten(): Flow<DeviceFile> =
children.transform {
when (it) {
is DeviceDirectory -> emitAll(it.flatten())
is DeviceFile -> emit(it)
}
}
@@ -1,165 +0,0 @@
/*
* Copyright (c) 2024 Auxio Project
* FileTreeCache.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.fs.device
import android.content.Context
import android.net.Uri
import android.util.Log
import java.io.File
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.serialization.Serializable
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
interface FileTreeCache {
fun read(): FileTree
companion object {
fun from(context: Context): FileTreeCache = FileTreeCacheImpl(context)
}
}
interface FileTree {
suspend fun queryDirectory(uri: Uri): CachedDirectory?
suspend fun updateDirectory(uri: Uri, directory: CachedDirectory)
suspend fun queryFile(uri: Uri): CachedFile?
suspend fun updateFile(uri: Uri, file: CachedFile)
suspend fun write()
}
// Define the sealed interface
@Serializable
private sealed interface FileSystemEntry {
val uri: String
val modifiedMs: Long
}
@Serializable
data class CachedDirectory(
override val uri: String,
val name: String,
override val modifiedMs: Long,
val subdirUris: List<String>,
val fileUris: List<String>
) : FileSystemEntry
@Serializable
data class CachedFile(
override val uri: String,
val name: String,
override val modifiedMs: Long,
val mimeType: String,
val size: Long
) : FileSystemEntry
@Serializable
private data class FileTreeData(
val directories: Map<String, CachedDirectory> = mapOf(),
val files: Map<String, CachedFile> = mapOf()
)
private class FileTreeCacheImpl(private val context: Context) : FileTreeCache {
companion object {
private const val CACHE_FILENAME = "file_tree_cache.json"
private val json = Json {
ignoreUnknownKeys = true
prettyPrint = true
}
}
override fun read(): FileTree {
val cacheFile = File(context.cacheDir, CACHE_FILENAME)
return if (cacheFile.exists()) {
try {
val jsonContent = cacheFile.readText()
val fileTreeCache = json.decodeFromString<FileTreeData>(jsonContent)
FileTreeImpl(
context,
fileTreeCache.directories.toMutableMap(),
fileTreeCache.files.toMutableMap())
} catch (e: Exception) {
FileTreeImpl(context, mutableMapOf(), mutableMapOf())
}
} else {
FileTreeImpl(context, mutableMapOf(), mutableMapOf())
}
}
}
private class FileTreeImpl(
private val context: Context,
private val mutableDirectories: MutableMap<String, CachedDirectory> = mutableMapOf(),
private val mutableFiles: MutableMap<String, CachedFile> = mutableMapOf()
) : FileTree {
companion object {
private const val TAG = "FileTree"
private const val CACHE_FILENAME = "file_tree_cache.json"
private val json = Json {
ignoreUnknownKeys = true
prettyPrint = true
}
}
// Directory operations
override suspend fun queryDirectory(uri: Uri): CachedDirectory? {
val uriString = uri.toString()
return mutableDirectories[uriString]
}
override suspend fun updateDirectory(uri: Uri, directory: CachedDirectory) {
val uriString = uri.toString()
mutableDirectories[uriString] = directory
}
// File operations
override suspend fun queryFile(uri: Uri): CachedFile? {
val uriString = uri.toString()
return mutableFiles[uriString]
}
override suspend fun updateFile(uri: Uri, file: CachedFile) {
val uriString = uri.toString()
mutableFiles[uriString] = file
}
override suspend fun write() =
withContext(Dispatchers.IO) {
Log.d(TAG, "Writing cache to disk")
val cacheFile = File(context.cacheDir, CACHE_FILENAME)
try {
val fileTreeCache =
FileTreeData(
directories = mutableDirectories.toMap(), files = mutableFiles.toMap())
val jsonContent = json.encodeToString(fileTreeCache)
cacheFile.writeText(jsonContent)
Log.d(TAG, "Successfully wrote cache to disk")
} catch (e: Exception) {
Log.e(TAG, "Failed to write cache file", e)
}
Unit
}
}
@@ -46,12 +46,8 @@ internal fun ContentResolver.safeQuery(
uri: Uri,
projection: Array<out String>,
selector: String? = null,
args: Array<String>? = null,
sortOrder: String? = null
) =
requireNotNull(query(uri, projection, selector, args, sortOrder)) {
"ContentResolver query failed"
}
args: Array<String>? = null
) = requireNotNull(query(uri, projection, selector, args, null)) { "ContentResolver query failed" }
/**
* A shortcut for [safeQuery] with [use] applied, automatically cleaning up the [Cursor]'s resources
@@ -72,6 +68,5 @@ internal inline fun <reified R> ContentResolver.useQuery(
projection: Array<out String>,
selector: String? = null,
args: Array<String>? = null,
sortOrder: String? = null,
block: (Cursor) -> R
) = safeQuery(uri, projection, selector, args, sortOrder).use(block)
) = safeQuery(uri, projection, selector, args).use(block)
@@ -1,64 +0,0 @@
# Metadata Package
## Overview
The metadata package provides the native bridge to TagLib and handles extraction of metadata from music files. This is a critical component that enables accurate and comprehensive tag parsing.
## Key Components
### JNI Interface
**TagLibJNI** (`TagLibJNI.kt`)
- Loads the native library
- Provides JNI methods for interacting with TagLib
- Handles native memory management
**NativeTagMap** (`NativeTagMap.kt`)
- Maps between native C++ and Java tag structures
- Provides type conversion utilities
**NativeInputStream** (`NativeInputStream.kt`)
- Provides a stream interface for TagLib to read file data
- Bridges between Java I/O and native code
### Metadata Extraction
**MetadataExtractor** (`MetadataExtractor.kt`)
- Extracts metadata from music files using TagLib
- Handles error cases and format-specific extractions
- Manages native resource lifecycle
**Metadata** (`Metadata.kt`)
- Container for extracted audio metadata
- Includes both tags and audio properties
**Properties** (part of `Metadata.kt`)
- Audio-specific properties like duration, sample rate, etc.
- Format-specific information
## Native Implementation
The C++ side of the metadata extraction is implemented in the `cpp` directory:
- **taglib_jni.cpp** - Main JNI implementation
- **JMetadataBuilder** - Builds metadata objects from TagLib
- **JTagMap** - Maps between Java and C++ tag structures
- **JInputStream** - Input stream adapter for TagLib
## Usage Flow
1. File is discovered in the exploration step
2. MetadataExtractor is called with the file
3. NativeInputStream provides file access to TagLib
4. TagLib parses the file's metadata
5. JMetadataBuilder converts TagLib structures to Java objects
6. Metadata object is returned to the pipeline
## Extension Points
When extending the metadata functionality:
1. For new tag formats, extend the native JNI code in `taglib_jni.cpp`
2. For new metadata fields, add them to both Java and native interfaces
3. For performance improvements, consider caching strategies in MetadataExtractor
4. Always ensure proper resource management with native code
@@ -1,79 +0,0 @@
# Model Package
## Overview
The model package implements the core music entity model for Musikr. It provides the structures that represent songs, albums, artists, genres, and playlists, as well as their relationships.
## Key Components
### Core Interfaces
These interfaces are defined in the parent package (`org.oxycblt.musikr`) and implemented in the model package:
- **Library** - Read-only representation of the music library
- **MutableLibrary** - Modifiable version of the library
- **Song** - Represents a music track
- **Album** - Represents an album
- **Artist** - Represents an artist
- **Genre** - Represents a music genre
- **Playlist** - Represents a playlist
### Implementations
**LibraryImpl** (`LibraryImpl.kt`)
- Implementation of the Library and MutableLibrary interfaces
- Manages collections of songs, albums, artists, genres, and playlists
- Provides search and lookup functionality
**SongImpl** (`SongImpl.kt`)
- Implementation of the Song interface
- Contains metadata, file information, and relationships
**AlbumImpl** (`AlbumImpl.kt`)
- Implementation of the Album interface
- Contains songs, artists, and album metadata
**ArtistImpl** (`ArtistImpl.kt`)
- Implementation of the Artist interface
- Contains songs, albums, and artist metadata
**GenreImpl** (`GenreImpl.kt`)
- Implementation of the Genre interface
- Contains songs and genre metadata
**PlaylistImpl** (`PlaylistImpl.kt`)
- Implementation of the Playlist interface
- Contains ordered songs and playlist metadata
### Factory
**LibraryFactory** (`LibraryFactory.kt`)
- Creates library instances from pipeline data
- Builds the entity relationships
- Resolves duplicates and conflicts
## Entity Relationships
The music model implements a graph structure with these relationships:
- Songs belong to albums, artists, and genres
- Albums belong to artists
- Artists have songs and albums
- Genres have songs
- Playlists have songs
## Key Features
- **Identity resolution** - Properly identifies and merges duplicate entities
- **Relationship building** - Creates the connections between entities
- **Immutable interfaces** - Provides read-only access for safety
- **Mutable implementation** - Allows controlled modifications
## Extension Points
When extending the model:
1. For new entity types, create new interfaces and implementations
2. For new relationships, update the appropriate entities and LibraryFactory
3. For performance improvements, consider optimizing the graph structure
4. For custom sorting or grouping, extend the LibraryImpl functionality
@@ -20,21 +20,17 @@ package org.oxycblt.musikr.pipeline
import android.content.Context
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.buffer
import kotlinx.coroutines.flow.emitAll
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.flatMapMerge
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.merge
import kotlinx.coroutines.flow.onCompletion
import org.oxycblt.musikr.Interpretation
import org.oxycblt.musikr.Query
import org.oxycblt.musikr.Storage
import org.oxycblt.musikr.cache.Cache
import org.oxycblt.musikr.cache.CacheResult
@@ -42,22 +38,20 @@ import org.oxycblt.musikr.cache.CachedSong
import org.oxycblt.musikr.covers.Cover
import org.oxycblt.musikr.covers.CoverResult
import org.oxycblt.musikr.covers.Covers
import org.oxycblt.musikr.fs.MusicLocation
import org.oxycblt.musikr.fs.device.DeviceFS
import org.oxycblt.musikr.fs.device.FileTreeCache
import org.oxycblt.musikr.fs.device.flatten
import org.oxycblt.musikr.playlist.db.StoredPlaylists
import org.oxycblt.musikr.playlist.m3u.M3U
internal interface ExploreStep {
fun explore(query: Query): Flow<Explored>
fun explore(locations: List<MusicLocation>): Flow<Explored>
companion object {
fun from(context: Context, storage: Storage, interpretation: Interpretation): ExploreStep =
ExploreStepImpl(
DeviceFS.from(context = context, withHidden = interpretation.withHidden),
DeviceFS.from(context, interpretation.withHidden),
storage.cache,
storage.covers,
storage.fileTreeCache,
storage.storedPlaylists)
}
}
@@ -66,18 +60,15 @@ private class ExploreStepImpl(
private val deviceFS: DeviceFS,
private val cache: Cache,
private val covers: Covers<out Cover>,
private val fileTreeCache: FileTreeCache,
private val storedPlaylists: StoredPlaylists
) : ExploreStep {
@OptIn(ExperimentalCoroutinesApi::class)
override fun explore(query: Query): Flow<Explored> {
override fun explore(locations: List<MusicLocation>): Flow<Explored> {
val addingMs = System.currentTimeMillis()
val fileTree = fileTreeCache.read()
return merge(
deviceFS
.explore(query, fileTree)
.flatMapMerge { it.flatten() }
.onCompletion { fileTree.write() }
.explore(
locations.asFlow(),
)
.filter { it.mimeType.startsWith("audio/") || it.mimeType == M3U.MIME_TYPE }
.distributedMap(n = 8, on = Dispatchers.IO, buffer = Channel.UNLIMITED) { file ->
when (val cacheResult = cache.read(file)) {
@@ -1,64 +0,0 @@
# Pipeline Package
## Overview
The pipeline package implements a three-stage processing pipeline for music indexing in Musikr. It provides a concurrent, efficient way to discover, extract metadata from, and process music files.
## Key Components
### Pipeline Steps
1. **ExploreStep** (`ExploreStep.kt`)
- Discovers music files on the device
- Interfaces with filesystem caches
- Produces `Explored` items for processing
2. **ExtractStep** (`ExtractStep.kt`)
- Extracts metadata from discovered files
- Uses TagLib via JNI for metadata extraction
- Produces `Extracted` items with parsed tags
3. **EvaluateStep** (`EvaluateStep.kt`)
- Processes extracted data to build the music library
- Creates the song/album/artist/genre relationships
- Resolves cover art references
### Pipeline Items
The `PipelineItem.kt` defines the data types that flow through the pipeline:
- **Explored** - Files discovered in the filesystem
- `NewSong` - A newly discovered music file
- `RawPlaylist` - A discovered playlist file
- **Extracted** - Files with extracted metadata
- `RawSong` - A song with extracted metadata and tags
- `InvalidSong` - A file that couldn't be processed
### Exception Handling
`PipelineException.kt` defines exceptions specific to the pipeline process.
## Flow Utilities
`FlowUtil.kt` provides utility functions for working with Kotlin Flows in the pipeline context, including:
- `distributedMap` - Parallel mapping operations
- Flow merging and buffering utilities
## Pipeline Flow
```
Location.Opened → ExploreStep → ExtractStep → EvaluateStep → Library
```
Data flows through the pipeline using Kotlin's Flow API, with extensive use of parallel processing and buffering to optimize performance.
## Extension Points
When extending the pipeline:
1. Consider the stage where your functionality belongs
2. Follow the existing pattern of `Flow<In> → Flow<Out>` transformations
3. Use the appropriate dispatchers for I/O vs CPU work
4. Buffer appropriately to manage backpressure
@@ -1,83 +0,0 @@
# Tag Package
## Overview
The tag package handles parsing, interpreting, and managing music metadata tags. It provides structures for representing various tag types and interpreting them according to user preferences.
## Key Components
### Tag Parsing
**TagParser** (`parse/TagParser.kt`)
- Parses raw tag data from the metadata extractor
- Handles different tag formats and structures
- Normalizes tags across different formats
**ParsedTags** (`parse/ParsedTags.kt`)
- Container for parsed metadata tags
- Provides structured access to tag values
**TagFields** (`parse/TagFields.kt`)
- Defines standard tag fields and their mapping
- Handles format-specific field names
### Tag Interpretation
**TagInterpreter** (`interpret/TagInterpreter.kt`)
- Interprets tags based on user preferences
- Resolves ambiguities in tag data
- Creates structured music metadata
**Naming** (`interpret/Naming.kt`)
- Handles naming conventions for music entities
- Provides fallbacks for missing metadata
**Separators** (`interpret/Separators.kt`)
- Handles multi-value separators in tags
- Splits tags with multiple artists, genres, etc.
**PreMusic** (`interpret/PreMusic.kt`)
- Intermediate representation during tag interpretation
- Holds partially processed music data
### Tag Types
**Name** (`Name.kt`)
- Represents artist, album, and track names
- Handles normalization and comparison
**Date** (`Date.kt`)
- Represents release dates
- Handles various date formats and partial dates
**Disc** (`Disc.kt`)
- Represents disc and track numbers
- Handles various numbering formats
**ReleaseType** (`ReleaseType.kt`)
- Represents album release types (album, EP, single, etc.)
- Handles format-specific release type tags
### Format-Specific Handling
**ID3** (`format/ID3.kt`)
- Handles ID3v1 and ID3v2 tag specifics
**Vorbis** (`format/Vorbis.kt`)
- Handles Vorbis Comment tag specifics
## Tag Flow
1. Raw tags extracted by the metadata extractor
2. TagParser normalizes tags into ParsedTags
3. TagInterpreter interprets tags based on user preferences
4. Interpreted tags are used to build the music library
## Extension Points
When extending the tag functionality:
1. For new tag types, extend the TagParser and relevant format handlers
2. For new interpretation rules, modify the TagInterpreter
3. For format-specific handling, add new format classes
4. For new metadata types, add appropriate structures and update the tag flow
@@ -22,11 +22,11 @@ import android.content.Context
import android.database.ContentObserver
import android.os.Handler
import android.os.Looper
import org.oxycblt.musikr.fs.Location
import org.oxycblt.musikr.fs.MusicLocation
internal class LocationObserver(
private val context: Context,
private val location: Location.Opened,
private val location: MusicLocation,
private val listener: UpdateTracker.Callback
) : ContentObserver(Handler(Looper.getMainLooper())), Runnable {
private val handler = Handler(Looper.getMainLooper())
@@ -19,15 +19,15 @@
package org.oxycblt.musikr.track
import android.content.Context
import org.oxycblt.musikr.fs.Location
import org.oxycblt.musikr.fs.MusicLocation
interface UpdateTracker {
fun track(locations: List<Location.Opened>)
fun track(locations: List<MusicLocation>)
fun release()
interface Callback {
fun onUpdate(location: Location.Opened)
fun onUpdate(location: MusicLocation)
}
companion object {
@@ -42,7 +42,7 @@ private class UpdateTrackerImpl(
) : UpdateTracker {
private val observers = mutableListOf<LocationObserver>()
override fun track(locations: List<Location.Opened>) {
override fun track(locations: List<MusicLocation>) {
release()
observers.addAll(locations.map { LocationObserver(context, it, callback) })
}