A mood with fewer tracks than a batch used to return an empty queue once the session had heard everything. Allow controlled replay of already-heard tracks once no unheard candidates remain, while still never repeating a track inside one batch and never leaving the owner's music folders.
AudioManager
A self-hosted, mood-first music server in Kotlin/Ktor, plus a Kotlin Multiplatform client.
AudioManager replaces static playlists with moods: curated anchors plus a radio queue that is generated live by the server and learns from what you finish and skip. There is no like button and no OpenSubsonic layer — the native API and the native client are designed together around this model.
Contents
- Quick start
- Configuration
- The mood model
- Native API
- Architecture
- Database
- Scanner
- Deployment
- Client
- Testing
- Roadmap
Quick start
Requirements: JDK 21, ffmpeg, SQLite (bundled through JDBC).
# 1. Build
gradle shadowJar
# 2. Point the server at a library
mkdir -p data
cat > config/library.yaml <<'YAML'
library:
folders:
- id: 1
name: Music
type: music
path: /absolute/path/to/music
- id: 10
name: Long-form
type: longform
path: /absolute/path/to/longform
YAML
# 3. Define users (passwords stay outside SQLite)
cat > config/users.yaml <<'YAML'
users:
- name: alice
password: change-me
admin: true
folders: [1]
YAML
# 4. Run
DATA_DIR=./data LIBRARY_CONFIG=./config/library.yaml USERS_FILE=./config/users.yaml \
java -jar build/libs/musicmanager-*-all.jar
The server exposes the native API under /api/v1; use the Kotlin Multiplatform client for browsing and playback. The first start scans the library automatically because the database is empty. Later scans are manual:
curl -X POST -H "Authorization: Bearer $TOKEN" http://localhost:8080/api/v1/scan
Configuration
library.yaml
library:
folders:
- id: 1
name: Music
type: music
path: /mnt/media/music
- id: 10
name: Long-form
type: longform
path: /mnt/media/longform
typeis eithermusicorlongform. They are never mixed in a mood.- IDs are stable and referenced by songs; never reuse an ID for a different path.
- Long-form folders are shared with every user automatically.
users.yaml
users:
- name: alice
password: change-me
admin: true
folders: [1]
- name: bob
password: another-secret
admin: false
folders: [1]
Passwords are read into memory at startup and never written to SQLite. In production this file is a Vault-managed Secret. Restart the deployment after changing users.
Environment
| Variable | Default | Meaning |
|---|---|---|
PORT |
8080 |
HTTP port |
DATA_DIR |
./data |
SQLite database and cover cache |
LIBRARY_CONFIG |
./config/library.yaml |
Library folders |
USERS_FILE |
./config/users.yaml |
Users and passwords |
FFMPEG_PATH |
ffmpeg |
Transcoder binary |
The mood model
A mood is a private collection owned by one user:
- Seeds are permanent anchors. Every seed is always eligible for the radio.
- Genres / free-text hint widen the candidate pool.
- Target size is the desired batch and session size, not a hard playlist length.
- Radio is generated by the server for each playback session. It mixes seeds, related genres and artists, text matches, and the rest of the owner's music.
- Signals come from playback: completed tracks gain weight, skipped tracks lose weight. There are no likes.
- Add to mood is explicit. The client offers add to current mood and choose another mood, and the server turns the track into a manual seed.
- Long-form is excluded at seed validation and radio generation.
A playback session belongs to one mood and one user. The server remembers queued tracks so a batch never repeats within the session, and a client can resume after a restart.
Native API
All endpoints live under /api/v1. JSON in, JSON out, standard HTTP status codes. Errors use:
{ "error": { "code": "not_found", "message": "Mood not found" } }
Authentication
POST /api/v1/auth/login
Content-Type: application/json
{ "username": "alice", "password": "change-me", "deviceName": "Pixel", "platform": "android" }
{
"token": "…",
"expiresAt": "2027-05-13T…",
"user": { "name": "alice", "admin": true, "musicFolders": [1], "longformFolders": [10] }
}
Send Authorization: Bearer <token> on every request. Tokens are stored as SHA-256 hashes and expire after 180 days. Media URLs may also use ?token= because HTML audio and <img> tags cannot set headers.
POST /auth/logoutrevokes the current token.GET /auth/deviceslists devices;DELETE /auth/devices/{id}revokes one.GET /mereturns the user and folder IDs.
Library sync
GET /library/songs?cursor=<id>&limit=500&scope=music|longform|all— snapshot page, ordered by song ID. Loop whilenextCursoris present.GET /library/songs?since=<revision>— delta withsongsanddeletedSongIds. Loop whilenextSinceis present.GET /library/search?q=&limit=&scope=— normalized substring search.GET /songs/{id}/stream— original MP3 with Range support. OptionalmaxBitRate,timeOffset,format,download=true.GET /covers/{albumIdOrSongId}?size=320— cached JPEG cover.
Song objects contain deterministic IDs (sg-…), album/artist names, duration, size, bitrate, genres, folderId, relativePath, and updatedAt, so a client can build an offline library without extra requests.
Moods
GET /moodsPOST /moods—{ name, description?, query?, genres[], targetSize, refreshHours, ytEnabled, seedSongIds[] }GET /moods/{id}— mood, seeds and recommendations.PATCH /moods/{id}— partial settings update;clearDescription/clearQueryclear fields.DELETE /moods/{id}POST /moods/{id}/seeds—{ songId }DELETE /moods/{id}/seeds/{songId}GET /moods/{id}/preview?limit=20— unpersisted radio preview.GET /moods/{id}/recommendations— YT Music candidates (see roadmap).
Radio sessions
POST /moods/{id}/sessions—{ limit?: 15 }→ session plus the first queue.GET /sessions/{id}— resume: session and queued tracks.POST /sessions/{id}/next—{ limit?, excludeSongIds[] }→ the next batch.POST /sessions/{id}/events—{ events: [{ songId, type: "started"|"completed"|"skipped", positionSeconds? }] }POST /sessions/{id}/add-to-mood—{ songId, moodId? }. WithoutmoodId, the session's mood is used. This is the replacement for likes.DELETE /sessions/{id}— close.
System
GET /scan—{ scanning, count, error }POST /scan— admin only; 202 Accepted.GET /health— unauthenticated liveness probe.
Architecture
src/main/kotlin/win/taptap/musicmanager/
|-- Application.kt # Ktor entry point, plugins, graceful shutdown
|-- config/
| |-- AppConfig.kt # Port, data dir, ffmpeg, env overrides
| |-- LibraryConfig.kt # Folder IDs, types and paths
| `-- UsersConfig.kt # Users, admins and folder assignments
|-- api/
| |-- ApiRoutes.kt # /api/v1 wiring, auth and system endpoints
| |-- ApiModels.kt # Native DTOs
| |-- ApiSupport.kt # Token resolution, errors, folder scoping
| |-- LibraryApi.kt # Sync, search, stream, covers
| |-- MoodApi.kt # Mood CRUD, seeds, preview, recommendations
| `-- SessionApi.kt # Radio sessions, events, add-to-mood
|-- radio/
| `-- RadioService.kt # Candidate pool, scoring, diversity, batches
|-- db/
| |-- DatabaseFactory.kt # SQLite WAL + Flyway
| |-- Tables.kt # Exposed definitions
| |-- ApiTokenRepository.kt # Hashed bearer tokens
| |-- RadioRepository.kt # Sessions, events, affinity
| |-- MoodRepository.kt # Moods, seeds, recommendations
| |-- LibraryRepository.kt # Scoped browsing, sync, search
| `-- MediaRepository.kt # Scanner persistence and tombstones
|-- scanner/ # Recursive MP3 scan, tags, covers
|-- transcoding/ # ffmpeg MP3 transcoding
`-- util/ # Deterministic IDs, sort names
The old OpenSubsonic layer (/rest, subsonic/, playlist materialization) was removed in 0.2.0. The server and the KMP client are the two halves of the same product; there is no compatibility layer to preserve and no server-rendered UI.
Database
SQLite in WAL mode, migrations through Flyway:
V1__init.sql— users, folders, artists, albums, songs, user state.V2__user_item_ratings.sql,V3__song_lyrics.sql.V4__moods.sql— the first playlist-based mood prototype.V5__native_api.sql— native moods, tokens, playback sessions, affinity, tombstones; drops playlists; addssongs.updated_at.
Key invariants:
- IDs are deterministic (
ar-,al-,sg-,mo-) with frozen normalization (NFC, trimmed, collapsed whitespace, lowercase). - Albums are grouped by album artist, not by track artist.
- Deleted songs leave tombstones so offline clients can remove them.
- Passwords never appear in the database.
Scanner
- Indexes
.mp3recursively; other extensions are skipped and logged. - Tags first,
Artist/Album/Trackpath fallback. - Delta scan: unchanged file mtimes are skipped.
- Orphan cleanup writes song tombstones.
- The first start scans automatically when the songs table is empty.
- Manual scans come from
POST /api/v1/scanor a client.
Deployment
Images and charts are published by Gitea Actions to gitea.tap-tap.win.
Image: gitea.tap-tap.win/taptap/audiomanager:<tag>
Chart: https://gitea.tap-tap.win/TapTap/Charts/raw/branch/main
Kustomize example:
helmCharts:
- name: audiomanager
repo: https://gitea.tap-tap.win/TapTap/Charts/raw/branch/main
releaseName: audiomanager
version: 0.2.0-sha.<commit>
namespace: audiomanager
valuesFile: values.yaml
The chart expects:
- a
users.yamlSecret (Vault-managed) referenced byusers.existingSecret; - a
library.yamlConfigMap; - read-only hostPaths for music and long-form;
- a registry pull secret for the private image.
Ingress host: subsonic.tap-tap.win (the historical name is kept, but the server no longer speaks the Subsonic protocol).
kustomize build --enable-helm . | kubectl apply -f -
kubectl -n audiomanager rollout status deployment/audiomanager
Flyway applies V5__native_api.sql automatically. Existing playlist-based moods are migrated to native moods; old playlists and user stars are dropped.
Client
The client lives in TapTap/AudioManagerClient and is built with Kotlin Multiplatform + Compose Multiplatform:
- Android: Media3/ExoPlayer, background playback, offline downloads.
- Desktop (JVM): shared Compose UI and a JVM audio backend.
- Web (Wasm): the same Compose UI, HTML audio, tokenized stream URLs.
The shared module owns the API client, auth store, SQLDelight offline database, mood radio queue, and platform player abstractions. Downloads are original MP3s from /stream?download=true. Web is streaming-only (the browser owns its cache).
Testing
gradle test # unit + API integration tests
GRADLE=gradle scripts/smoke.sh # end-to-end server smoke test
The smoke test generates tagged MP3s, starts the server, and verifies login, sync, moods, radio, add-to-mood, streaming, transcoding, covers, scan and logout.
Roadmap
- MP3 scanner, covers, deterministic IDs, SQLite + Flyway.
- Native bearer-auth API, sync deltas, tombstones.
- Mood CRUD, seeds, server-driven radio, playback events, add-to-mood.
- Kotlin Multiplatform client foundation (Android, desktop, web).
- Offline downloads and offline playback across clients.
- YT Music discovery through
yt-dlp, recommendation list, accept/reject. - Optional downloader that writes accepted tracks into an import folder and rescans.
- Home-screen widgets, Android Auto, and richer radio tuning.