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 ## 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 ### Prerequisites
- `cmake` and `ninja-build` must be installed before building - Unix-based system (cannot build on Windows)
- Project uses git submodules - clone with `git clone --recurse-submodules` - Install `cmake` and `ninja-build`
- **Cannot build on Windows** - requires Unix-based system for Media3 build scripts - Clone with submodules: `git clone --recurse-submodules`
### Common Build Commands ### Build Commands
```bash ```bash
# Build debug version # Build debug APK
./gradlew assembleDebug ./gradlew assembleDebug
# Build release version # Build release APK
./gradlew assembleRelease ./gradlew assembleRelease
# Run tests # Clean build
./gradlew test ./gradlew clean build
# Run connected tests # Install debug build on device
./gradlew connectedAndroidTest ./gradlew installDebug
# Code formatting (Spotless)
./gradlew spotlessApply
# Check code formatting
./gradlew spotlessCheck
``` ```
### Development Modules ### Code Quality Commands
- `app/` - Main Android application ```bash
- `musikr/` - Native music indexing library with TagLib integration # Check code formatting (MUST pass before committing)
- `media/` - Patched Media3 ExoPlayer libraries (git submodule) ./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 ## Architecture Overview
### Core Architecture Pattern ### High-Level Architecture
- **MVVM** with ViewModels for each major screen (Home, Detail, Playback, Search) - **Pattern**: MVVM (Model-View-ViewModel) with Dagger Hilt dependency injection
- **Repository Pattern** - MusicRepository as single source of truth for music data - **Navigation**: Single Activity architecture with Navigation Component
- **Dependency Injection** - Hilt/Dagger for modular dependency management - **UI**: Material Design 3 with edge-to-edge display
- **Single Activity Architecture** with Navigation Components - **Data**: Repository pattern with Room database and custom Musikr library
- **Service-Oriented** background music processing - **Playback**: MediaBrowserServiceCompat with vendored Media3/ExoPlayer
### Key Modules & Components ### Key Components
#### Music Management (`app/src/main/java/org/oxycblt/auxio/music/`) #### Service Architecture
- `MusicRepository` - Central music library state management - `AuxioService` - Main MediaBrowserService for background playback
- `MusicViewModel` - UI layer for music data access - `PlaybackServiceFragment` - Handles all playback operations
- `service/` - MediaBrowserServiceCompat integration - `MusicServiceFragment` - Manages music browsing and library
- `shim/` - Abstraction layer for musikr integration
#### Playback Engine (`app/src/main/java/org/oxycblt/auxio/playback/`) #### Data Layer
- `PlaybackViewModel` - Main playback UI interface - `MusicRepository` - Primary interface for music data access
- `PlaybackStateManager` - Core playback state management - `PersistenceRepository` - Handles playback state and playlists
- `service/` - Background ExoPlayer integration - `Musikr` - Custom music indexing library (separate module)
- `queue/` - Playback queue management - Bypasses MediaStore limitations
- `persist/` - Playback state persistence (Room database) - Supports advanced metadata and tags
- `replaygain/` - Audio processing for volume normalization - Background indexing with progress
#### UI Structure (`app/src/main/java/org/oxycblt/auxio/`) #### UI Layer Structure
- `home/` - Main library browsing with customizable tabs ```
- `detail/` - Album, artist, genre, and playlist detail views app/src/main/java/org/oxycblt/auxio/
- `search/` - Music search functionality ├── MainActivity.kt # Single activity host
- `list/` - Shared list components with sorting/filtering ├── MainFragment.kt # Main container with bottom sheets
- `ui/` - Custom UI components, theming, animations ├── 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/`) #### State Management
- **Pipeline-based indexing** - Multi-stage scanning (Explore → Extract → Evaluate) - StateFlow/MutableStateFlow for reactive state
- **TagLib integration** - Native C++ metadata extraction - Shared ViewModels between fragments
- **File system caching** - Device storage access optimization - Event wrapper pattern for one-time UI events
- **Cover art management** - Embedded and external cover support - Lifecycle-aware observers
### Data Flow ### Navigation Flow
1. musikr scans and indexes music files from device storage 1. `MainActivity` hosts all navigation
2. MusicRepository manages indexed library and exposes to UI 2. Two navigation graphs: `inner.xml` (main) and `outer.xml` (onboarding)
3. ViewModels provide reactive state for UI components using StateFlow 3. Bottom sheet for playback UI
4. PlaybackService handles audio playback via ExoPlayer 4. Dialog destinations for popups
5. UI observes ViewModels and updates reactively
## 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 ## Important Development Notes
- **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
### Code Style ### Code Style
- Uses Spotless with ktfmt Dropbox style formatting - Kotlin code formatted with ktfmt (Dropbox style)
- License header required (see NOTICE file) - C++ code uses Eclipse CDT formatting
- C++ code uses Eclipse CDT formatting (eclipse-cdt.xml) - 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 ### Architectural Constraints
- Unit tests: `src/test/` directories - Stick to F-Droid inclusion guidelines
- Integration tests: `src/androidTest/` directories - No proprietary dependencies
- musikr module includes Robolectric tests - Feature additions unlikely to be accepted
- Major UI changes discouraged
### Test Dependencies ### Testing Requirements
- JUnit 4 for unit testing - Test all changes thoroughly
- MockK for mocking - Unit tests for business logic
- Robolectric for Android unit tests - Consider edge cases for music metadata
- Espresso for UI tests - 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 ### Custom Modifications
- **Native Dependencies**: musikr module builds TagLib from source during compilation - Vendored/patched Media3 in `media/` directory
- **Permission Handling**: Requires storage permissions for music file access - Custom patches for ExoPlayer features
- **Background Services**: Foreground service for continuous music playback - Modified libraries shouldn't be updated directly
- **Widget Support**: Multiple widget layouts with automatic sizing adaptation
- **ReplayGain**: Full support for MP3, FLAC, OGG, OPUS, and MP4 files
+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 │ Application Layer │
2. **Extract Step** - Extracts metadata from discovered files │ (Auxio or other apps) │
3. **Evaluate Step** - Processes extracted data to build the music library └───────────────────────────┬─────────────────────────────────┘
│
```mermaid ▼
graph LR ┌─────────────────────────────────────────────────────────────┐
A[Music Locations] --> B[Explore Step] │ Musikr API │
B --> C[Extract Step] │ (Musikr.kt interface) │
C --> D[Evaluate Step] └───────────────────────────┬─────────────────────────────────┘
D --> E[Library] │
▼
subgraph Pipeline ┌─────────────────────────────────────────────────────────────┐
B │ Pipeline Architecture │
C │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
D │ │ ExploreStep │ → │ ExtractStep │ → │ EvaluateStep │ │
end │ └──────────────┘ └──────────────┘ └──────────────┘ │
└─────────────────────────────────────────────────────────────┘
│
┌───────────┴───────────┐
│ │
▼ ▼
┌──────────────────────┐ ┌──────────────────────────────┐
│ 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 ### 1. ExploreStep
- **Storage** - Manages persistent storage needs - **Purpose**: Discover music files on the device
- **Library** - Represents the loaded music collection - **Process**:
- **MutableLibrary** - Modifiable version of the library - 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) ### 3. EvaluateStep
- **Location.Opened** - Represents a location to search for music - **Purpose**: Build the music graph from extracted metadata
- **DeviceFS** - Provides access to device storage - **Process**:
- **FileTreeCache** - Caches filesystem structure for faster indexing - 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) ## Key Components
- **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) ### Config & Storage
- **Metadata** - Extracted file metadata - **Config**: Main configuration container
- **MetadataExtractor** - Extracts metadata using TagLib - `fs`: File system access configuration
- **TagLibJNI** - JNI bridge to native TagLib library - `storage`: Persistent storage components
- `interpretation`: Tag interpretation rules
### 4. Tag Processing (`tag` package) - **Storage**: Side-effect laden components
- **TagParser** - Parses raw tag data into structured format - `cache`: Metadata caching (Room database)
- **TagInterpreter** - Interprets tags based on user preferences - `covers`: Cover art storage and retrieval
- **ParsedTags** - Represents parsed metadata tags - `storedPlaylists`: User playlist management
### 5. Model (`model` package) ### Data Models
- **LibraryImpl** - Implementation of the music library - **Music**: Base interface for all music items
- **SongImpl**, **AlbumImpl**, **ArtistImpl**, **GenreImpl** - Music entity implementations - Uses UID system for unique identification
- **LibraryFactory** - Creates library instances from pipeline data - 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) ### File System (FS)
- **Covers** - Interface for album cover management - Abstraction over Android's Storage Access Framework
- **EmbeddedCovers** - Extracts covers embedded in music files - Supports multiple storage locations
- **FSCovers** - Discovers cover art in the filesystem - Handles permissions and URI management
- **StoredCovers** - Manages persistent storage of covers
### 7. Cache (`cache` package) ### Native Layer (C++)
- **Cache** - Caches processed music data - TagLib integration for metadata extraction
- **DBCache** - Database implementation of caching - JNI wrappers for Java/Kotlin interop
- Support for various audio formats
### 8. Playlist (`playlist` package) - Custom patches for enhanced functionality
- **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 ## 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 ## Performance Optimizations
- Bounded buffer channels manage backpressure - **Caching**: Aggressive metadata caching
- IO operations are dispatched to `Dispatchers.IO` - **Parallel processing**: Multi-threaded file processing
- **Lazy evaluation**: On-demand cover loading
## Best Practices for Extension - **Memory efficiency**: Streaming pipeline architecture
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
+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