musikr: add agent lodestones

Useful for making changes with amp/claude.
This commit is contained in:
Alexander Capehart
2025-05-29 20:55:25 -06:00
parent 294c3eb304
commit 7f672d63da
8 changed files with 661 additions and 0 deletions
+135
View File
@@ -0,0 +1,135 @@
# 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)
- **MusicLocation** - 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
+90
View File
@@ -0,0 +1,90 @@
# 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
@@ -0,0 +1,74 @@
# 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
@@ -0,0 +1,72 @@
# 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
**MusicLocation** (`MusicLocation.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 `MusicLocation`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
@@ -0,0 +1,64 @@
# 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
@@ -0,0 +1,79 @@
# 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
@@ -0,0 +1,64 @@
# 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
```
MusicLocation → 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
@@ -0,0 +1,83 @@
# 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