info: agent files, mk 2

This commit is contained in:
Alexander Capehart
2025-06-28 18:28:13 -06:00
parent 93d755b8d4
commit 96761ac990
5 changed files with 938 additions and 202 deletions
+129 -87
View File
@@ -4,120 +4,162 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
## Project Overview
Auxio is a modern Android music player written in Kotlin that emphasizes simplicity and performance. It uses Media3 ExoPlayer for playback and includes a custom native music indexing library called musikr.
Auxio is a simple, rational music player for Android built on Media3 ExoPlayer. It features gapless playback, ReplayGain support, Android Auto integration, and advanced music indexing capabilities.
## Build System & Commands
## Essential Build Commands
### Prerequisites
- `cmake` and `ninja-build` must be installed before building
- Project uses git submodules - clone with `git clone --recurse-submodules`
- **Cannot build on Windows** - requires Unix-based system for Media3 build scripts
- Unix-based system (cannot build on Windows)
- Install `cmake` and `ninja-build`
- Clone with submodules: `git clone --recurse-submodules`
### Common Build Commands
### Build Commands
```bash
# Build debug version
# Build debug APK
./gradlew assembleDebug
# Build release version
# Build release APK
./gradlew assembleRelease
# Run tests
./gradlew test
# Clean build
./gradlew clean build
# Run connected tests
./gradlew connectedAndroidTest
# Code formatting (Spotless)
./gradlew spotlessApply
# Check code formatting
./gradlew spotlessCheck
# Install debug build on device
./gradlew installDebug
```
### Development Modules
- `app/` - Main Android application
- `musikr/` - Native music indexing library with TagLib integration
- `media/` - Patched Media3 ExoPlayer libraries (git submodule)
### Code Quality Commands
```bash
# Check code formatting (MUST pass before committing)
./gradlew spotlessCheck
# Apply code formatting fixes
./gradlew spotlessApply
# Run Android lint
./gradlew lint
# Run lint with automatic fixes
./gradlew lintFix
```
### Testing Commands
```bash
# Run unit tests
./gradlew test
# Run debug unit tests
./gradlew testDebugUnitTest
# Run musikr module tests specifically
./gradlew musikr:testDebug
# Run instrumentation tests (requires device/emulator)
./gradlew connectedAndroidTest
```
### Development Workflow
```bash
# Before committing: format code and run checks
./gradlew spotlessApply
./gradlew check
# Run a single test class
./gradlew test --tests "org.oxycblt.auxio.YourTestClass"
# Run a single test method
./gradlew test --tests "org.oxycblt.auxio.YourTestClass.yourTestMethod"
```
## Architecture Overview
### Core Architecture Pattern
- **MVVM** with ViewModels for each major screen (Home, Detail, Playback, Search)
- **Repository Pattern** - MusicRepository as single source of truth for music data
- **Dependency Injection** - Hilt/Dagger for modular dependency management
- **Single Activity Architecture** with Navigation Components
- **Service-Oriented** background music processing
### High-Level Architecture
- **Pattern**: MVVM (Model-View-ViewModel) with Dagger Hilt dependency injection
- **Navigation**: Single Activity architecture with Navigation Component
- **UI**: Material Design 3 with edge-to-edge display
- **Data**: Repository pattern with Room database and custom Musikr library
- **Playback**: MediaBrowserServiceCompat with vendored Media3/ExoPlayer
### Key Modules & Components
### Key Components
#### Music Management (`app/src/main/java/org/oxycblt/auxio/music/`)
- `MusicRepository` - Central music library state management
- `MusicViewModel` - UI layer for music data access
- `service/` - MediaBrowserServiceCompat integration
- `shim/` - Abstraction layer for musikr integration
#### Service Architecture
- `AuxioService` - Main MediaBrowserService for background playback
- `PlaybackServiceFragment` - Handles all playback operations
- `MusicServiceFragment` - Manages music browsing and library
#### Playback Engine (`app/src/main/java/org/oxycblt/auxio/playback/`)
- `PlaybackViewModel` - Main playback UI interface
- `PlaybackStateManager` - Core playback state management
- `service/` - Background ExoPlayer integration
- `queue/` - Playback queue management
- `persist/` - Playback state persistence (Room database)
- `replaygain/` - Audio processing for volume normalization
#### Data Layer
- `MusicRepository` - Primary interface for music data access
- `PersistenceRepository` - Handles playback state and playlists
- `Musikr` - Custom music indexing library (separate module)
- Bypasses MediaStore limitations
- Supports advanced metadata and tags
- Background indexing with progress
#### UI Structure (`app/src/main/java/org/oxycblt/auxio/`)
- `home/` - Main library browsing with customizable tabs
- `detail/` - Album, artist, genre, and playlist detail views
- `search/` - Music search functionality
- `list/` - Shared list components with sorting/filtering
- `ui/` - Custom UI components, theming, animations
#### UI Layer Structure
```
app/src/main/java/org/oxycblt/auxio/
├── MainActivity.kt # Single activity host
├── MainFragment.kt # Main container with bottom sheets
├── home/ # Home screen tabs (songs, albums, artists, etc.)
├── detail/ # Detail screens for albums/artists
├── playback/ # Playback UI and controls
├── search/ # Search functionality
├── settings/ # Preferences screens
├── list/ # Reusable list components
└── music/ # Music data models and repository
```
#### Native Music Library (`musikr/`)
- **Pipeline-based indexing** - Multi-stage scanning (Explore → Extract → Evaluate)
- **TagLib integration** - Native C++ metadata extraction
- **File system caching** - Device storage access optimization
- **Cover art management** - Embedded and external cover support
#### State Management
- StateFlow/MutableStateFlow for reactive state
- Shared ViewModels between fragments
- Event wrapper pattern for one-time UI events
- Lifecycle-aware observers
### Data Flow
1. musikr scans and indexes music files from device storage
2. MusicRepository manages indexed library and exposes to UI
3. ViewModels provide reactive state for UI components using StateFlow
4. PlaybackService handles audio playback via ExoPlayer
5. UI observes ViewModels and updates reactively
### Navigation Flow
1. `MainActivity` hosts all navigation
2. Two navigation graphs: `inner.xml` (main) and `outer.xml` (onboarding)
3. Bottom sheet for playback UI
4. Dialog destinations for popups
## Code Conventions
### Dependency Injection Setup
- `@HiltAndroidApp` on Auxio application class
- `@AndroidEntryPoint` on activities/fragments
- Modules: `MusicModule`, `PlaybackModule`, `UIModule`
- Scoped with `@Singleton` for app-wide instances
### Language & Libraries
- **Kotlin** - Primary language with coroutines for async operations
- **Hilt/Dagger** - Dependency injection
- **Room** - Local database for persistence
- **Navigation Components** - Fragment navigation
- **ViewBinding** - Type-safe view access
- **StateFlow/LiveData** - Reactive state management
- **Coil** - Image loading for cover art
## Important Development Notes
### Code Style
- Uses Spotless with ktfmt Dropbox style formatting
- License header required (see NOTICE file)
- C++ code uses Eclipse CDT formatting (eclipse-cdt.xml)
- Kotlin code formatted with ktfmt (Dropbox style)
- C++ code uses Eclipse CDT formatting
- Spotless enforces formatting automatically
- License headers required (enforced by Spotless)
## Testing
### Git Workflow
- Default branch: `dev` (development)
- PRs should target `dev` branch
- `master` contains stable releases only
### Test Structure
- Unit tests: `src/test/` directories
- Integration tests: `src/androidTest/` directories
- musikr module includes Robolectric tests
### Architectural Constraints
- Stick to F-Droid inclusion guidelines
- No proprietary dependencies
- Feature additions unlikely to be accepted
- Major UI changes discouraged
### Test Dependencies
- JUnit 4 for unit testing
- MockK for mocking
- Robolectric for Android unit tests
- Espresso for UI tests
### Testing Requirements
- Test all changes thoroughly
- Unit tests for business logic
- Consider edge cases for music metadata
- Test on different Android versions (min SDK 24)
## Key Development Notes
### Key Libraries
- AndroidX Navigation, Room, Media3
- Dagger Hilt for DI
- Kotlin Coroutines for async
- Coil for image loading
- Material Design Components 3
- **Custom Media3**: Uses patched Media3 ExoPlayer for enhanced playback features
- **Native Dependencies**: musikr module builds TagLib from source during compilation
- **Permission Handling**: Requires storage permissions for music file access
- **Background Services**: Foreground service for continuous music playback
- **Widget Support**: Multiple widget layouts with automatic sizing adaptation
- **ReplayGain**: Full support for MP3, FLAC, OGG, OPUS, and MP4 files
### Custom Modifications
- Vendored/patched Media3 in `media/` directory
- Custom patches for ExoPlayer features
- Modified libraries shouldn't be updated directly
+105 -115
View File
@@ -1,135 +1,125 @@
# Musikr Architecture
# Musikr Architecture Overview
## Overview
Musikr is a highly opinionated, multi-threaded music loading library for Android that bypasses Android's MediaStore and uses the Storage Access Framework (SAF) with TagLib for enhanced music indexing capabilities.
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 Design Principles
## Core Components
1. **Stateless API**: Side-effects are contained within the Storage layer
2. **No Defaults**: All parameters must be explicitly configured
3. **Pipeline Architecture**: Three-step processing pipeline for music loading
4. **Native Integration**: JNI bridge to TagLib for metadata extraction
5. **Coroutine-Based**: Uses Kotlin coroutines for async operations
### Pipeline Architecture
## High-Level 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
```
┌─────────────────────────────────────────────────────────────┐
│ Application Layer │
│ (Auxio or other apps) │
└───────────────────────────┬─────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ Musikr API │
│ (Musikr.kt interface) │
└───────────────────────────┬─────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ Pipeline Architecture │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ ExploreStep │ → │ ExtractStep │ → │ EvaluateStep │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
└─────────────────────────────────────────────────────────────┘
│
┌───────────┴───────────┐
│ │
▼ ▼
┌──────────────────────┐ ┌──────────────────────────────┐
│ Storage Layer │ │ Native Layer (JNI) │
│ - Cache │ │ - TagLib integration │
│ - Covers │ │ - Metadata extraction │
│ - Playlists │ │ - Format support │
└──────────────────────┘ └──────────────────────────────┘
```
### Key Interfaces
## Pipeline Steps
- **Musikr** - Main entry point for the library
- **Storage** - Manages persistent storage needs
- **Library** - Represents the loaded music collection
- **MutableLibrary** - Modifiable version of the library
### 1. ExploreStep
- **Purpose**: Discover music files on the device
- **Process**:
- Uses FS module to explore file system via SAF
- Filters for audio MIME types and playlists
- Checks cache for previously indexed files
- Manages cover art retrieval
- **Output**: Stream of `Explored` items (songs/playlists to process)
## Module Structure
### 2. ExtractStep
- **Purpose**: Extract metadata from discovered files
- **Process**:
- Uses JNI bridge to TagLib for metadata extraction
- Handles multiple tag formats (ID3v1/v2, MP4, Xiph, etc.)
- Extracts audio properties (bitrate, duration, etc.)
- Manages cover art extraction
- **Output**: Stream of `Extracted` items with full metadata
### 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
### 3. EvaluateStep
- **Purpose**: Build the music graph from extracted metadata
- **Process**:
- Creates relationships between songs, albums, artists, genres
- Resolves naming conflicts and duplicates
- Applies user interpretation preferences
- Builds final library structure
- **Output**: Complete `MutableLibrary` with all relationships
### 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
## Key Components
### 3. Metadata (`metadata` package)
- **Metadata** - Extracted file metadata
- **MetadataExtractor** - Extracts metadata using TagLib
- **TagLibJNI** - JNI bridge to native TagLib library
### Config & Storage
- **Config**: Main configuration container
- `fs`: File system access configuration
- `storage`: Persistent storage components
- `interpretation`: Tag interpretation rules
### 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
- **Storage**: Side-effect laden components
- `cache`: Metadata caching (Room database)
- `covers`: Cover art storage and retrieval
- `storedPlaylists`: User playlist management
### 5. Model (`model` package)
- **LibraryImpl** - Implementation of the music library
- **SongImpl**, **AlbumImpl**, **ArtistImpl**, **GenreImpl** - Music entity implementations
- **LibraryFactory** - Creates library instances from pipeline data
### Data Models
- **Music**: Base interface for all music items
- Uses UID system for unique identification
- Supports MusicBrainz IDs
- **Song**: Individual track with full metadata
- **Album**: Collection of songs (includes EPs, singles, etc.)
- **Artist**: Can have explicit (album artist) and implicit (track artist) albums
- **Genre**: Grouping by musical genre
- **Playlist**: User-created or imported playlists
### 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
### File System (FS)
- Abstraction over Android's Storage Access Framework
- Supports multiple storage locations
- Handles permissions and URI management
### 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
```
### Native Layer (C++)
- TagLib integration for metadata extraction
- JNI wrappers for Java/Kotlin interop
- Support for various audio formats
- Custom patches for enhanced functionality
## Threading Model
- **Coroutine-based**: All operations use Kotlin coroutines
- **Multi-threaded extraction**: Parallel metadata extraction
- **Buffered channels**: For efficient pipeline communication
- **Dispatcher control**: Explicit IO dispatcher usage
Musikr uses Kotlin Coroutines for concurrent processing:
## Error Handling
- **Pipeline exceptions**: Custom exception types
- **Graceful degradation**: Continue on individual file errors
- **Logging**: Comprehensive error logging
- **Cache invalidation**: Automatic stale cache detection
- 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
## Performance Optimizations
- **Caching**: Aggressive metadata caching
- **Parallel processing**: Multi-threaded file processing
- **Lazy evaluation**: On-demand cover loading
- **Memory efficiency**: Streaming pipeline architecture
+306
View File
@@ -0,0 +1,306 @@
# Musikr Data Flow Diagram
This document illustrates how data flows through the Musikr music loading pipeline from file discovery to final library creation.
## Overview Flow
```
┌─────────────────┐
│ User Request │
│ Musikr.run() │
└────────┬────────┘
│
▼
┌─────────────────────────────────────────────────────────┐
│ EXPLORE PHASE │
│ │
│ File System ──► SAF APIs ──► Audio Files │
│ │ │ │
│ └──► Cached Files ◄─────────┘ │
│ │ │
│ ▼ │
│ Cover Cache ──► Explored Items │
└─────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────┐
│ EXTRACT PHASE │
│ │
│ Explored Items ──► JNI Bridge ──► TagLib │
│ │ │ │
│ ▼ ▼ │
│ Native Code Tag Parsing │
│ │ │ │
│ └────────────┘ │
│ │ │
│ ▼ │
│ Metadata Maps │
│ │ │
│ ▼ │
│ Extracted Items │
└─────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────┐
│ EVALUATE PHASE │
│ │
│ Extracted Items ──► Graph Builder ──► Relationships │
│ │ │ │
│ ▼ ▼ │
│ Name Resolution UID Generation │
│ │ │ │
│ └────────────────┘ │
│ │ │
│ ▼ │
│ MutableLibrary │
└─────────────────────────────────────────────────────────┘
```
## Detailed Phase Flows
### 1. Explore Phase Data Flow
```
START: FS.explore()
│
▼
┌─────────────────┐
│ Storage Access │
│ Framework │
└────────┬────────┘
│ DocumentFile
▼
┌─────────────────┐ ┌─────────────────┐
│ Audio Filter │ │ Playlist Filter │
│ (audio/* MIME) │ │ (M3U MIME) │
└────────┬────────┘ └────────┬────────┘
│ │
▼ ▼
┌─────────────────────────────────────────┐
│ Cache Lookup │
│ ┌─────────────┐ ┌──────────────┐ │
│ │ Cache Hit │ │ Cache Miss │ │
│ │ (Metadata) │ │ (New File) │ │
│ └──────┬──────┘ └──────┬───────┘ │
│ │ │ │
│ ▼ ▼ │
│ ┌─────────────┐ ┌──────────────┐ │
│ │Cover Lookup │ │ Mark for │ │
│ │ if Hit │ │ Extraction │ │
│ └──────┬──────┘ └──────┬───────┘ │
└─────────┴─────────────────┴─────────────┘
│
▼
Explored Stream
(Flow<Explored>)
```
### 2. Extract Phase Data Flow
```
START: Explored Items
│
▼
┌─────────────────┐
│ Group by Type │
│ - NewSong │
│ - RawSong │
│ - RawPlaylist │
└────────┬────────┘
│
┌────┴────┐
│ NewSong │
└────┬────┘
│
▼
┌─────────────────────────────────────┐
│ JNI Metadata Call │
│ │
│ Kotlin ──► JNI ──► C++ ──► TagLib │
│ │ │ │
│ └─────── Results ◄────────┘ │
└─────────────────────────────────────┘
│
▼
┌─────────────────────────────────────┐
│ Metadata Processing │
│ ┌──────────────┐ ┌──────────────┐ │
│ │ Properties │ │ Tags │ │
│ │ - Duration │ │ - Title │ │
│ │ - Bitrate │ │ - Artist │ │
│ │ - Format │ │ - Album │ │
│ └──────────────┘ └──────────────┘ │
└─────────────────────────────────────┘
│
▼
┌─────────────────────────────────────┐
│ Cache Update │
│ - Write metadata to cache │
│ - Store cover reference │
└─────────────────────────────────────┘
│
▼
Extracted Stream
(Flow<Extracted>)
```
### 3. Evaluate Phase Data Flow
```
START: Extracted Items
│
▼
┌─────────────────────────────────────┐
│ Collect All Items │
│ - Songs │
│ - Playlists │
└────────┬────────────────────────────┘
│
▼
┌─────────────────────────────────────┐
│ UID Generation/Resolution │
│ ┌──────────────┐ ┌──────────────┐ │
│ │ MusicBrainz │ │ Hash-based │ │
│ │ UIDs │ │ UIDs │ │
│ └──────────────┘ └──────────────┘ │
└────────┬────────────────────────────┘
│
▼
┌─────────────────────────────────────┐
│ Name Interpretation │
│ - Apply naming rules │
│ - Parse separators │
│ - Resolve conflicts │
└────────┬────────────────────────────┘
│
▼
┌─────────────────────────────────────────────┐
│ Graph Building │
│ │
│ Songs ──► Albums ──► Artists │
│ │ │ │ │
│ └──────► Genres ◄────┘ │
│ │
│ Relationships: │
│ - Song.album → Album │
│ - Song.artists → List<Artist> │
│ - Album.artists → List<Artist> │
│ - Artist.albums → List<Album> │
└──────────────┬──────────────────────────────┘
│
▼
┌─────────────────────────────────────┐
│ Playlist Resolution │
│ - Match paths to songs │
│ - Create playlist objects │
└────────┬────────────────────────────┘
│
▼
┌─────────────────────────────────────┐
│ Final Library │
│ MutableLibrary { │
│ songs: List<Song> │
│ albums: List<Album> │
│ artists: List<Artist> │
│ genres: List<Genre> │
│ playlists: List<Playlist> │
│ } │
└─────────────────────────────────────┘
```
## Key Data Transformations
### File → Explored
```
DocumentFile { Explored {
uri: Uri ──► file: DocumentFile
mimeType: String // + cache status
} }
```
### Explored → Extracted
```
NewSong { ExtractedSong {
file: DocumentFile ──► file: DocumentFile
addedMs: Long properties: Properties
} tags: Map<String, List<String>>
cover: Cover?
addedMs: Long
}
```
### Extracted → Library Items
```
ExtractedSong { Song {
tags: Map ──► uid: UID
properties: Props name: Name
} album: Album
artists: List<Artist>
// ... full metadata
}
```
## Caching Data Flow
```
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ File URI │ ──► │ Cache Key │ ──► │ Cached │
│ │ │ Generation │ │ Metadata │
└─────────────┘ └─────────────┘ └─────────────┘
│
┌────────────────────┴────────────┐
│ │
┌─────▼─────┐ ┌─────▼─────┐
│ Valid │ │ Stale │
│ Use Cached │ │ Re-extract│
└───────────┘ └───────────┘
```
## Cover Art Data Flow
```
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Embedded │ │ Cover ID │ │ Cover │
│ Cover Data │ ──► │ Generation │ ──► │ Cache │
└─────────────┘ └─────────────┘ └─────────────┘
│
▼
┌─────────────┐
│ Cover Ref │
│ in Library │
└─────────────┘
```
## Error Handling Flow
```
┌─────────────┐
│ Error │
│ Occurs │
└──────┬──────┘
│
▼
┌─────────────────────────────────┐
│ Error Classification │
│ ┌──────────┐ ┌─────────────┐ │
│ │ Critical │ │ Recoverable │ │
│ └────┬─────┘ └──────┬──────┘ │
└───────┴────────────────┴────────┘
│ │
▼ ▼
┌──────────────┐ ┌───────────────┐
│ Stop Pipeline│ │ Log & Continue│
│ Throw Error │ │ Skip Item │
└──────────────┘ └───────────────┘
```
## Progress Reporting Flow
```
Pipeline Stage ──► Progress Event ──► Callback
│
▼
IndexingProgress
├── Songs(loaded, explored)
└── Indeterminate
```
+249
View File
@@ -0,0 +1,249 @@
# Musikr Module Breakdown
This document provides a detailed breakdown of all modules and packages within the Musikr library.
## Package Structure
```
org.oxycblt.musikr/
├── cache/ # Metadata caching system
├── covers/ # Cover art management
├── fs/ # File system abstraction
├── graph/ # Music relationship graph
├── metadata/ # JNI metadata extraction
├── model/ # Concrete implementations
├── pipeline/ # Processing pipeline
├── playlist/ # Playlist management
├── tag/ # Tag interpretation
├── track/ # Change tracking
└── util/ # Utility functions
```
## Core Modules
### Main Entry Points
#### `Musikr.kt`
- Main interface for the library
- Factory methods for creating instances
- Defines `LibraryResult` and `IndexingProgress`
#### `Config.kt`
- Configuration data classes
- `Config`: Main configuration container
- `Storage`: Side-effect components
- `Interpretation`: Tag parsing rules
#### `Music.kt`
- Core music data interfaces
- `Music`: Base interface with UID system
- `Song`, `Album`, `Artist`, `Genre`, `Playlist` interfaces
- UID implementation with MusicBrainz support
#### `Library.kt`
- Library container interfaces
- `Library`: Read-only music library
- `MutableLibrary`: Mutable library for updates
## Pipeline Modules (`pipeline/`)
### `PipelineItem.kt`
- Data classes for pipeline communication
- `Explored`: Items found during exploration
- `Extracted`: Items with extracted metadata
- `NewSong`, `RawSong`, `RawPlaylist` types
### `ExploreStep.kt`
- First pipeline stage
- Discovers music files using FS module
- Integrates with cache for optimization
- Handles cover pre-loading
### `ExtractStep.kt`
- Second pipeline stage
- Calls native metadata extraction
- Manages metadata caching
- Handles extraction failures
### `EvaluateStep.kt`
- Final pipeline stage
- Builds music graph from extracted data
- Resolves relationships between items
- Creates final library structure
### `FlowUtil.kt`
- Coroutine flow utilities
- `distributedMap`: Parallel processing helper
## File System Module (`fs/`)
### `FS.kt`
- File system abstraction interface
- SAF integration for Android
- Multi-location support
### `Path.kt`
- Path representation and manipulation
- Volume and document separation
- Display-friendly path formatting
### `Location.kt`
- Storage location management
- Permission handling
- URI to path conversion
### `Format.kt`
- Audio format enumeration
- MIME type mapping
- Format detection utilities
## Metadata Module (`metadata/`)
### `TagLibJNI.kt`
- JNI interface to native code
- Native method declarations
### `MetadataExtractor.kt`
- High-level metadata extraction
- Format-specific extraction routing
- Error handling and fallbacks
### `Metadata.kt`
- Metadata container classes
- Properties and tag maps
- Type-safe metadata access
### Native Integration
- `NativeInputStream.kt`: Java InputStream to C++ bridge
- `NativeTagMap.kt`: Tag data transfer object
## Cache Module (`cache/`)
### `Cache.kt`
- Cache interfaces and data types
- `CacheResult`: Hit/Miss/Stale states
- Read/write operations
### Implementation (not shown in detail)
- Room database integration
- Metadata persistence
- Cache invalidation logic
## Cover Module (`covers/`)
### `Covers.kt`
- Cover art management interfaces
- `CoverResult`: Cover loading states
- Cleanup operations
### `Cover.kt`
- Cover identifier types
- Format information
- Collection utilities
## Tag Module (`tag/`)
### Tag Types
- `Date.kt`: Date parsing and representation
- `Disc.kt`: Disc number handling
- `Name.kt`: Name types (Known/Unknown)
- `ReleaseType.kt`: Album type classification
- `ReplayGainAdjustment.kt`: ReplayGain data
### Interpretation (`tag/interpret/`)
- `Naming.kt`: Name construction rules
- `Separators.kt`: Multi-value tag parsing
## Model Module (`model/`)
Concrete implementations of music interfaces:
- `SongImpl.kt`: Song data implementation
- `AlbumImpl.kt`: Album with song relationships
- `ArtistImpl.kt`: Artist with album relationships
- `GenreImpl.kt`: Genre grouping implementation
- `PlaylistImpl.kt`: Playlist container
- `LibraryImpl.kt`: Complete library implementation
- `LibraryFactory.kt`: Factory for creating library instances
## Graph Module (`graph/`)
### `MusicGraph.kt`
- Relationship graph builder
- Artist-album-song connections
- Genre associations
- Duplicate resolution
## Playlist Module (`playlist/`)
### `ExternalPlaylistManager.kt`
- External playlist loading
- Format detection and parsing
### `PlaylistFile.kt`
- Playlist file abstraction
- Common playlist operations
### `m3u/M3U.kt`
- M3U/M3U8 playlist support
- Path resolution
- Encoding handling
### `db/StoredPlaylists.kt`
- Database playlist interface
- CRUD operations
- Persistence management
## Track Module (`track/`)
### `UpdateTracker.kt`
- File system change detection
- Modification tracking
- Update notification
### `LocationObserver.kt`
- Storage location monitoring
- Permission change handling
## Utility Module (`util/`)
### `LangUtil.kt`
- Language/locale utilities
- String manipulation helpers
### `ParseUtil.kt`
- Parsing utilities
- Number parsing with validation
- UUID parsing
## Native Layer (C++)
### JNI Wrappers
- `JByteArrayRef`: Byte array management
- `JClassRef`: Class reference caching
- `JInputStream`: Stream adapter
- `JMetadataBuilder`: Metadata assembly
- `JObjectRef`: Object lifecycle management
- `JStringRef`: String conversion
- `JTagMap`: Tag data transfer
### Main JNI Entry
- `taglib_jni.cpp`: Native method implementations
- Format-specific parsing functions
- Error handling and logging
### Build System
- `CMakeLists.txt`: Native build configuration
- `build_taglib.sh`: TagLib compilation script
- `android.toolchain.cmake`: Android-specific toolchain
## Testing
### Unit Tests (`test/`)
- Tag parsing tests
- Date/Disc/ReleaseType validation
- Utility function tests
### Integration
- Full pipeline testing
- Cache behavior verification
- Cover loading tests
+149
View File
@@ -0,0 +1,149 @@
# Musikr Quick Reference Guide
## What is Musikr?
A custom Android music indexing library that bypasses MediaStore, using SAF + TagLib for enhanced metadata extraction and music organization.
## Key Features
- **No MediaStore**: Direct file access via Storage Access Framework
- **Advanced Metadata**: Full TagLib integration for rich tag support
- **Multi-threaded**: Parallel processing with Kotlin coroutines
- **Smart Caching**: Efficient metadata and cover art caching
- **MusicBrainz Support**: Proper handling of MB IDs
- **Flexible Architecture**: Pipeline-based processing
## Quick Start
```kotlin
// 1. Configure storage components
val storage = Storage(
cache = myCache,
covers = myCoverManager,
storedPlaylists = myPlaylistDb
)
// 2. Set interpretation rules
val interpretation = Interpretation(
naming = Naming.SYSTEM, // or DISPLAY
separators = Separators.default()
)
// 3. Create config
val config = Config(
fs = myFileSystem,
storage = storage,
interpretation = interpretation
)
// 4. Run musikr
val musikr = Musikr.new(context, config)
val result = musikr.run { progress ->
// Handle progress updates
}
// 5. Use the library
val library = result.library
println("Found ${library.songs.size} songs")
// 6. Clean up
result.cleanup()
```
## Core Concepts
### Pipeline Architecture
1. **Explore**: Find music files
2. **Extract**: Get metadata via TagLib
3. **Evaluate**: Build music graph
### Data Model
- **Song**: Individual tracks with full metadata
- **Album**: Collections of songs (includes EPs, singles)
- **Artist**: Can have both album and track credits
- **Genre**: Musical style groupings
- **Playlist**: User-created or imported (M3U)
### UID System
- Unique identifiers for all music items
- Supports MusicBrainz IDs
- Hash-based fallback for untagged files
## File Structure
```
musikr/
├── src/main/
│ ├── java/ # Kotlin sources
│ └── cpp/ # Native TagLib integration
├── ARCHITECTURE.md # System design overview
├── MODULES.md # Detailed module docs
└── DATA_FLOW.md # Data flow diagrams
```
## Common Tasks
### Custom Cache Implementation
```kotlin
class MyCache : MutableCache {
override suspend fun read(file: DocumentFile): CacheResult {
// Your implementation
}
override suspend fun write(extracted: List<ExtractedSong>) {
// Your implementation
}
}
```
### Custom Cover Storage
```kotlin
class MyCovers : MutableCovers<MyCover> {
override suspend fun obtain(id: String): CoverResult<MyCover> {
// Your implementation
}
override suspend fun write(cover: Cover): String {
// Your implementation
}
}
```
### Progress Monitoring
```kotlin
musikr.run { progress ->
when (progress) {
is IndexingProgress.Songs -> {
println("Loaded ${progress.loaded}/${progress.explored}")
}
is IndexingProgress.Indeterminate -> {
println("Building library...")
}
}
}
```
## Important Notes
1. **No Windows Support**: Requires Unix-based build system
2. **GPL v3 License**: Viral license - entire project must be GPL
3. **Unstable API**: Interface may change between versions
4. **Thread Safety**: All operations are coroutine-safe
5. **Memory Usage**: Streaming architecture for large libraries
## Debugging Tips
- Enable TagLib debug output for metadata issues
- Check cache validity for performance problems
- Monitor coroutine dispatchers for threading issues
- Use flow operators for custom processing
## Performance Tuning
- Adjust `distributedMap` parallelism (default: 8)
- Configure channel buffer sizes
- Optimize cache implementation
- Pre-warm cover cache for common albums
## See Also
- [ARCHITECTURE.md](ARCHITECTURE.md) - System design
- [MODULES.md](MODULES.md) - Module details
- [DATA_FLOW.md](DATA_FLOW.md) - Data flow diagrams
- [README.md](README.md) - Basic information