8 Commits
Author SHA1 Message Date
TapTap 4d5a97cdac fix: make finish-this-track win over prefetched audio
CI / build (push) Successful in 4m4s
CI / play (push) Successful in 3m24s
Stop half a second before the boundary so ExoPlayer cannot start the next item,
report the final completed event, and show offline download progress in mood
settings. Version 0.4.2.
2026-11-19 17:11:41 +00:00
TapTap 8e737fae2e fix: mirror a live service timeline after the UI is recreated
CI / build (push) Successful in 3m59s
CI / play (push) Successful in 3m27s
The media service can keep playing after the task is swiped. A new UI now
adopts its queue, index and position instead of showing a stale paused state.
Notification artwork also uses cached offline covers. Version 0.4.1.
2026-11-19 16:58:20 +00:00
TapTap 8cf77f156d fix: avoid duplicate playback events at the end of the timeline
CI / play (push) Successful in 3m38s
CI / build (push) Successful in 3m55s
Also prefer the freshest mood detail during offline sync and reset the skip
suppression after a previous that only restarted the track.
2026-11-19 16:41:41 +00:00
TapTap 1e3dac4e47 feat: service-owned queue, full player, audio consistency and mood settings
CI / build (push) Successful in 2m40s
CI / play (push) Skipped
- Android Media3 service owns a real timeline: gapless playback, notification
  and headset next/back, 2 s previous rule, queue survives task swipes
- per-track loudness gain via an Android PCM processor and desktop mixer
- optional 0-8 s fade between tracks; full-screen player with quality info
- per-mood offline switch auto-syncs songs on Wi-Fi, three at a time
- dedicated mood settings screen with delete at the bottom
- one-tap add-to-mood in the player; sleep timer can finish the current track
- version 0.4.0
2026-11-19 16:38:21 +00:00
TapTap 8d7f6a0ccb fix: re-run search immediately when the mood source changes
CI / build (push) Successful in 3m54s
CI / play (push) Successful in 3m29s
The explicit source switch cancelled the debounced search and then waited
another 300 ms for no reason. It now searches right away, which also makes the
test deterministic.
2026-11-18 19:48:09 +00:00
TapTap 4048262fc5 feat: remove the Up next preview section
CI / build (push) Successful in 2m22s
CI / play (push) Skipped
The preview duplicated what the radio does and is not the real queue. Mood
detail now only loads songs and recommendations, so opening a mood makes one
fewer request.

Also drop the Wasm warm-up from the CI image recipe: the target is local-only.
Version 0.3.3.
2026-11-18 19:39:51 +00:00
TapTap 14e5b9d982 ci: drop the Wasm build from the pipeline
CI / build (push) Successful in 2m57s
CI / play (push) Skipped
It is CPU-bound and dominates the runtime. The target stays available for
local builds with :composeApp:wasmJsBrowserDistribution.
2026-11-18 19:26:04 +00:00
TapTap e28e95fa2b fix: notification skip/back drive the app queue
CI / build (push) Successful in 14m12s
CI / play (push) Successful in 3m20s
- advertise next/previous on a ForwardingPlayer so the notification and
  Android Auto show the buttons, and route them to the mood queue
- rename the preview section to 'Up next' with a clearer subtitle
- version 0.3.2
2026-11-18 19:14:05 +00:00
28 changed files with 2209 additions and 718 deletions

No files matched your search

+2 -5
View File
@@ -45,15 +45,13 @@ jobs:
:composeApp:desktopTest \ :composeApp:desktopTest \
:composeApp:assembleDebug \ :composeApp:assembleDebug \
:composeApp:packageUberJarForCurrentOS \ :composeApp:packageUberJarForCurrentOS \
:composeApp:wasmJsBrowserDistribution \
--console=plain --console=plain
else else
# The optimized Wasm build is CPU-bound and slow; main/PR builds # The Wasm target is kept for local builds but is not part of CI:
# only need to prove the web target compiles and bundles. # it is CPU-bound and dominates the pipeline runtime.
gradle \ gradle \
:composeApp:desktopTest \ :composeApp:desktopTest \
:composeApp:assembleDebug \ :composeApp:assembleDebug \
:composeApp:wasmJsBrowserDevelopmentExecutableDistribution \
--console=plain --console=plain
fi fi
@@ -64,7 +62,6 @@ jobs:
cp composeApp/build/outputs/apk/debug/composeApp-debug.apk dist/AudioManager.apk cp composeApp/build/outputs/apk/debug/composeApp-debug.apk dist/AudioManager.apk
if [[ "$GITHUB_REF" == refs/tags/* ]]; then if [[ "$GITHUB_REF" == refs/tags/* ]]; then
cp composeApp/build/compose/jars/*.jar dist/AudioManager-desktop.jar cp composeApp/build/compose/jars/*.jar dist/AudioManager-desktop.jar
(cd composeApp/build/dist/wasmJs/productionExecutable && zip -qr "$GITHUB_WORKSPACE/dist/AudioManager-web.zip" .)
fi fi
- name: Publish release assets - name: Publish release assets
+33 -22
View File
@@ -37,25 +37,33 @@ a server-driven radio session and songs are added from Deezer or YouTube Music.
same mood session. same mood session.
- Playback events are reported automatically (`started`, `completed`, `skipped`) - Playback events are reported automatically (`started`, `completed`, `skipped`)
so the server learns. so the server learns.
- Two add-to-mood actions in the player: - **Add to mood is one tap** in the bottom player and the full-screen player.
- **Add to current mood** (the mood of the active radio session) Choosing a different mood stays in the overflow/picker.
- **Choose another mood** (picker)
- A queue sheet from the player: the current track is pinned, upcoming tracks - A queue sheet from the player: the current track is pinned, upcoming tracks
can be reordered by **long-press and drag** or removed. Changes are persisted can be reordered by **long-press and drag** or removed. Changes are persisted
locally. locally.
- **Previous** from the player: after two seconds of playback it restarts the - **Previous** from the player: after two seconds of playback it restarts the
current track; before that it restores the last played track. current track; before that it restores the last played track.
- **Headset/Bluetooth next and previous** use the same queue rules as the - **Headset/Bluetooth next and previous** and the media notification's skip /
buttons; they no longer seek inside the single ExoPlayer item. back buttons use the same queue rules as the in-app controls; they no longer
- The bottom player keeps the cover and title/artist readable on narrow phones; seek inside the single ExoPlayer item.
add-to-mood actions moved into the overflow menu. - The bottom player keeps the cover and title/artist readable on narrow phones.
Tapping it opens the **full-screen player**: large artwork, scrubber, transport,
add-to-mood, queue, sleep timer and Up next.
- **Audio consistency**: the server measures every track's integrated loudness
with ffmpeg and stores a gain (target `-16 LUFS`); the app applies it per
track. The player shows the source and bitrate, and settings explain when the
Deezer ARL is limited to 128 kbps.
- **Gapless playback** on Android with an optional 0–8 s fade between tracks.
- **Scrubbing**: the progress slider can be dragged on every platform. Android and - **Scrubbing**: the progress slider can be dragged on every platform. Android and
web seek natively; desktop restarts the decoder at the requested position. web seek natively; desktop restarts the decoder at the requested position.
- **Mood settings**: name, description, discovery hint, genres, collection share, - **Mood settings** live on their own screen: name, description, discovery hint,
active recommendation count (0–30), and refresh interval. genres, source, collection share, recommendations, refresh interval, a
**Keep this mood offline** switch, and Delete at the bottom.
- **Downloads** screen for device-side copies: play, delete, clear, storage - **Downloads** screen for device-side copies: play, delete, clear, storage
usage. usage.
- **Sleep timer** (15/30/45/60/90 minutes) that pauses playback. On Android the - **Sleep timer** (15/30/45/60/90 minutes or **finish this track**) that pauses
playback. On Android the
pause is scheduled inside the media service, so it still fires when the app is pause is scheduled inside the media service, so it still fires when the app is
backgrounded or the task is swiped away. backgrounded or the task is swiped away.
- Mood cache: moods and details are stored locally so the app opens instantly - Mood cache: moods and details are stored locally so the app opens instantly
@@ -71,7 +79,7 @@ a server-driven radio session and songs are added from Deezer or YouTube Music.
## Screens ## Screens
`Moods | Mood Detail | Search | Downloads | Settings` `Moods | Mood Detail | Mood settings | Search | Downloads | Settings | Now playing`
- **Moods** — grid with song and pick counts, create, global search. - **Moods** — grid with song and pick counts, create, global search.
- **Mood Detail** — songs, add music, recommendations, next batch, settings. - **Mood Detail** — songs, add music, recommendations, next batch, settings.
@@ -79,7 +87,8 @@ a server-driven radio session and songs are added from Deezer or YouTube Music.
downloaded badges and an inline Downloading… / Added / Failed status per downloaded badges and an inline Downloading… / Added / Failed status per
result, so the keyboard never hides the feedback. result, so the keyboard never hides the feedback.
- **Downloads** — offline files and storage usage. - **Downloads** — offline files and storage usage.
- **Settings** — account, server URL, offline storage, sign out. - **Settings** — account, server URL, audio (normalization, crossfade, source
quality), offline storage and auto-synced moods, sign out.
There is no Library tab, no Longform tab and no global shuffle. There is no Library tab, no Longform tab and no global shuffle.
@@ -132,7 +141,7 @@ gradle :composeApp:run
# Desktop fat jar # Desktop fat jar
gradle :composeApp:packageUberJarForCurrentOS gradle :composeApp:packageUberJarForCurrentOS
# Web bundle # Web bundle (local only, not built by CI)
gradle :composeApp:wasmJsBrowserDistribution gradle :composeApp:wasmJsBrowserDistribution
# composeApp/build/dist/wasmJs/productionExecutable # composeApp/build/dist/wasmJs/productionExecutable
``` ```
@@ -199,7 +208,7 @@ Tagged builds (`v*`) publish to internal testing from CI. The Gitea secrets are:
| `ANDROID_KEY_PASSWORD` | key password | | `ANDROID_KEY_PASSWORD` | key password |
| `PLAY_SERVICE_ACCOUNT_JSON` | contents of the service account JSON | | `PLAY_SERVICE_ACCOUNT_JSON` | contents of the service account JSON |
Then `git tag v0.3.1 && git push --tags` builds, signs and uploads the bundle. Then `git tag v0.4.2 && git push --tags` builds, signs and uploads the bundle.
Gradle Play Publisher asks Play for the next free `versionCode` Gradle Play Publisher asks Play for the next free `versionCode`
(`ResolutionStrategy.AUTO`), so only the tag/version name needs to change. (`ResolutionStrategy.AUTO`), so only the tag/version name needs to change.
@@ -249,11 +258,11 @@ radio and visible in the song list.
`gitea.tap-tap.win/taptap/audiomanager-client-ci:3`. The image has the Android `gitea.tap-tap.win/taptap/audiomanager-client-ci:3`. The image has the Android
SDK, Node, Yarn and a warmed Gradle dependency cache. SDK, Node, Yarn and a warmed Gradle dependency cache.
- **main / PR:** run `desktopTest`, build the Android APK and the *development* - **main / PR:** run `desktopTest` and build the Android APK.
Wasm bundle. - **`v*` tag:** additionally build the desktop fat jar, attach the artifacts to
- **`v*` tag:** additionally build the desktop fat jar and the optimized Wasm the Gitea release, and publish the AAB to Play internal testing.
bundle, attach the artifacts to the Gitea release, and publish the AAB to Play - The Wasm target stays in the project for local builds but is **not** part of
internal testing. CI; compiling it dominates the pipeline runtime.
Rebuild the CI image after changing `ci/Dockerfile` or dependency versions: Rebuild the CI image after changing `ci/Dockerfile` or dependency versions:
@@ -263,9 +272,11 @@ scripts/build-ci-image.sh 3
## Known limitations ## Known limitations
- The media notification exposes play/pause and seeking. Queue actions (skip, - The media notification exposes play/pause, skip and back from the timeline.
add to mood) stay in the app because the mood session and its events belong to Adding to a mood stays in the app because the session and its events belong to
the server. the server. The queue lives in the Android media service, but the *next batch*
still comes from the app process; if the process is killed, the known queue
keeps working but nothing more is fetched.
- Desktop playback supports seeking by reopening the decoder at the requested - Desktop playback supports seeking by reopening the decoder at the requested
position. MP3s are decoded to 16-bit PCM before the line is opened, because position. MP3s are decoded to 16-bit PCM before the line is opened, because
Java Sound has no line for the compressed format. Java Sound has no line for the compressed format.
+4 -9
View File
@@ -43,21 +43,16 @@ RUN mkdir -p "$ANDROID_HOME/cmdline-tools" \
"build-tools;36.0.0" \ "build-tools;36.0.0" \
&& rm -rf "$ANDROID_HOME/.temp" "$ANDROID_HOME/.downloadIntermediates" && rm -rf "$ANDROID_HOME/.temp" "$ANDROID_HOME/.downloadIntermediates"
# Warm the Gradle dependency cache and the Kotlin/Wasm (node, yarn, binaryen) # Warm the Gradle dependency cache and the common/Android/desktop compilers so
# toolchain so CI jobs do not download them on every run. Rebuild this image # CI jobs do not download them on every run. The Wasm toolchain is intentionally
# when dependencies change. # not warmed: Wasm is not part of the pipeline. Rebuild this image when
# dependencies change.
COPY . /warmup COPY . /warmup
WORKDIR /warmup WORKDIR /warmup
# Warm dependencies and the common/Android/desktop compilers here. The Wasm
# executable build is memory hungry and stays in the web job, but node and yarn
# are cached: Kotlin downloads them from GitHub, which has been flaky during CI.
RUN sed -i 's/kotlin.daemon.jvmargs=-Xmx3g/kotlin.daemon.jvmargs=-Xmx2g/' gradle.properties \ RUN sed -i 's/kotlin.daemon.jvmargs=-Xmx3g/kotlin.daemon.jvmargs=-Xmx2g/' gradle.properties \
&& gradle --no-daemon --max-workers=2 \ && gradle --no-daemon --max-workers=2 \
:kotlinNodeJsSetup \
:kotlinYarnSetup \
:composeApp:desktopTest \ :composeApp:desktopTest \
:composeApp:assembleDebug \ :composeApp:assembleDebug \
:composeApp:compileKotlinWasmJs \
--console=plain \ --console=plain \
&& rm -rf /warmup && rm -rf /warmup
+1 -1
View File
@@ -41,7 +41,7 @@ val hasUploadKey = uploadKeyStore?.exists() == true &&
val appVersionCode = (System.getenv("VERSION_CODE") ?: localProperties.getProperty("VERSION_CODE") ?: "1").toInt() val appVersionCode = (System.getenv("VERSION_CODE") ?: localProperties.getProperty("VERSION_CODE") ?: "1").toInt()
val appVersionName = System.getenv("VERSION_NAME") val appVersionName = System.getenv("VERSION_NAME")
?: localProperties.getProperty("VERSION_NAME") ?: localProperties.getProperty("VERSION_NAME")
?: "0.3.1" ?: "0.4.2"
kotlin { kotlin {
androidTarget { androidTarget {
@@ -2,6 +2,7 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"> <manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" /> <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" /> <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
@@ -0,0 +1,105 @@
package win.taptap.musicmanager.client
import android.content.Context
import androidx.media3.common.C
import androidx.media3.common.audio.AudioProcessor
import androidx.media3.common.audio.AudioProcessor.AudioFormat
import androidx.media3.common.util.UnstableApi
import androidx.media3.exoplayer.DefaultRenderersFactory
import androidx.media3.exoplayer.audio.AudioSink
import androidx.media3.exoplayer.audio.DefaultAudioSink
import java.nio.ByteBuffer
import java.nio.ByteOrder
import kotlin.math.pow
/**
* Applies the server's per-track loudness gain to 16-bit PCM.
*
* ExoPlayer's own volume is limited to 0..1, so it can only attenuate. Measuring
* tracks against -16 LUFS needs small positive gains on quiet recordings too;
* scaling the PCM samples supports both directions while leaving the hardware
* volume untouched.
*/
@UnstableApi
class GainAudioProcessor : AudioProcessor {
@Volatile
var gain: Float = 1f
private var inputFormat: AudioFormat = AudioFormat.NOT_SET
private var outputFormat: AudioFormat = AudioFormat.NOT_SET
private var buffer: ByteBuffer = AudioProcessor.EMPTY_BUFFER
private var endOfStream = false
override fun configure(inputAudioFormat: AudioFormat): AudioFormat {
if (inputAudioFormat.encoding != C.ENCODING_PCM_16BIT) {
// Float output or compressed passthrough: leave the samples alone.
inputFormat = AudioFormat.NOT_SET
outputFormat = AudioFormat.NOT_SET
return AudioFormat.NOT_SET
}
inputFormat = inputAudioFormat
outputFormat = inputAudioFormat
return outputFormat
}
override fun isActive(): Boolean = inputFormat != AudioFormat.NOT_SET
override fun queueInput(inputBuffer: ByteBuffer) {
val value = gain
val output = ByteBuffer.allocateDirect(inputBuffer.remaining())
.order(ByteOrder.nativeOrder())
while (inputBuffer.remaining() >= 2) {
val sample = inputBuffer.short.toInt()
val scaled = (sample * value).toInt()
.coerceIn(Short.MIN_VALUE.toInt(), Short.MAX_VALUE.toInt())
output.putShort(scaled.toShort())
}
output.flip()
buffer = output
}
override fun queueEndOfStream() {
endOfStream = true
}
override fun getOutput(): ByteBuffer = buffer
override fun isEnded(): Boolean = endOfStream && !buffer.hasRemaining()
override fun flush() {
buffer = AudioProcessor.EMPTY_BUFFER
endOfStream = false
}
override fun reset() {
buffer = AudioProcessor.EMPTY_BUFFER
endOfStream = false
inputFormat = AudioFormat.NOT_SET
outputFormat = AudioFormat.NOT_SET
}
companion object {
fun fromDb(db: Double): Float =
10.0.pow(db / 20.0).toFloat().coerceIn(0f, 4f)
}
}
/** Wires the gain processor into ExoPlayer's audio sink. */
@UnstableApi
class GainRenderersFactory(
context: Context,
private val gainProcessor: GainAudioProcessor,
) : DefaultRenderersFactory(context) {
override fun buildAudioSink(
context: Context,
enableFloatOutput: Boolean,
enableAudioTrackPlaybackParams: Boolean,
): AudioSink = DefaultAudioSink.Builder(context)
.setAudioProcessors(arrayOf(gainProcessor))
// The processor works on 16-bit PCM; forcing float output would bypass it.
.setEnableFloatOutput(false)
.setEnableAudioTrackPlaybackParams(enableAudioTrackPlaybackParams)
.build()
}
@@ -10,8 +10,8 @@ import androidx.media3.common.MediaMetadata
import androidx.media3.common.Player import androidx.media3.common.Player
import androidx.media3.session.MediaController import androidx.media3.session.MediaController
import androidx.media3.session.SessionToken import androidx.media3.session.SessionToken
import win.taptap.musicmanager.client.api.Song
import win.taptap.musicmanager.client.playback.AudioPlayer import win.taptap.musicmanager.client.playback.AudioPlayer
import win.taptap.musicmanager.client.playback.PlaybackTrack
/** /**
* Client side of [PlaybackService]. The controller is created asynchronously; * Client side of [PlaybackService]. The controller is created asynchronously;
@@ -55,43 +55,56 @@ class MediaControllerAudioPlayer(context: Context) : AudioPlayer {
) )
} }
override fun play( override fun setQueue(tracks: List<PlaybackTrack>, startIndex: Int, startAtSeconds: Double) {
source: String, if (tracks.isEmpty()) return
song: Song,
local: Boolean,
artworkUri: String?,
artworkBytes: ByteArray?,
) {
finished = false finished = false
withController { controller -> val items = tracks.map(::mediaItem)
val uri = if (local) Uri.fromFile(java.io.File(source)) else Uri.parse(source) val index = startIndex.coerceIn(tracks.indices)
val metadata = MediaMetadata.Builder() val positionMs = (startAtSeconds * 1_000).toLong().coerceAtLeast(0L)
.setTitle(song.title) withController { current ->
.setArtist(song.artist) current.setMediaItems(items, index, positionMs)
.setAlbumTitle(song.album) current.prepare()
.apply { current.play()
if (artworkBytes != null && artworkBytes.isNotEmpty()) {
setArtworkData(
artworkBytes,
MediaMetadata.PICTURE_TYPE_FRONT_COVER,
)
} else {
setArtworkUri(artworkUri?.let(Uri::parse))
}
}
.build()
val item = MediaItem.Builder()
.setUri(uri)
.setMimeType("audio/mpeg")
.setMediaMetadata(metadata)
.build()
controller.setMediaItem(item)
controller.prepare()
controller.play()
} }
} }
override fun appendToQueue(tracks: List<PlaybackTrack>) {
if (tracks.isEmpty()) return
val items = tracks.map(::mediaItem)
withController { current -> current.addMediaItems(items) }
}
override fun moveInQueue(fromIndex: Int, toIndex: Int) {
withController { current -> current.moveMediaItem(fromIndex, toIndex) }
}
override fun removeAt(index: Int) {
withController { current -> current.removeMediaItem(index) }
}
override fun playIndex(index: Int, startAtSeconds: Double) {
finished = false
val positionMs = (startAtSeconds * 1_000).toLong().coerceAtLeast(0L)
withController { current ->
if (index in 0 until current.mediaItemCount) {
current.seekTo(index, positionMs)
current.play()
}
}
}
override fun skipToNext() {
withController { current -> current.seekToNextMediaItem() }
}
override fun skipToPrevious(restartAfterSeconds: Double) {
withController { current -> current.seekToPreviousMediaItem() }
}
override fun currentIndex(): Int = controller?.currentMediaItemIndex ?: 0
override fun queueSize(): Int = controller?.mediaItemCount ?: 0
override fun pause() { override fun pause() {
withController { it.pause() } withController { it.pause() }
} }
@@ -126,19 +139,26 @@ class MediaControllerAudioPlayer(context: Context) : AudioPlayer {
withController { it.seekTo((seconds * 1000).toLong().coerceAtLeast(0L)) } withController { it.seekTo((seconds * 1000).toLong().coerceAtLeast(0L)) }
} }
override fun setSkipCallbacks(onNext: (() -> Unit)?, onPrevious: (() -> Unit)?) { override val supportsCrossfade: Boolean = true
PlaybackCommands.onNext = onNext
PlaybackCommands.onPrevious = onPrevious override fun setCrossfadeSeconds(seconds: Int) {
val args = Bundle().apply { putInt(CROSSFADE_SECONDS, seconds.coerceAtLeast(0)) }
withController { current ->
runCatching { current.sendCustomCommand(CROSSFADE_COMMAND, args) }
}
} }
override fun scheduleSleepTimer(seconds: Long?): Boolean { override fun scheduleSleepTimer(seconds: Long?): Boolean {
val args = Bundle().apply { putLong(SLEEP_TIMER_SECONDS, seconds ?: 0L) } val args = Bundle().apply { putLong(SLEEP_TIMER_SECONDS, seconds ?: 0L) }
val send: (MediaController) -> Boolean = { current -> val send: (MediaController) -> Unit = { current ->
runCatching { current.sendCustomCommand(SLEEP_TIMER_COMMAND, args) }.isSuccess runCatching { current.sendCustomCommand(SLEEP_TIMER_COMMAND, args) }
} }
val current = controller val current = controller
if (current != null && connected) return send(current) if (current != null && connected) {
synchronized(pending) { pending.addLast { controller -> send(controller) } } send(current)
return true
}
synchronized(pending) { pending.addLast(send) }
return true return true
} }
@@ -150,13 +170,42 @@ class MediaControllerAudioPlayer(context: Context) : AudioPlayer {
synchronized(pending) { pending.clear() } synchronized(pending) { pending.clear() }
} }
private fun mediaItem(track: PlaybackTrack): MediaItem {
val uri = if (track.local) {
Uri.fromFile(java.io.File(track.source))
} else {
Uri.parse(track.source)
}
val metadata = MediaMetadata.Builder()
.setTitle(track.song.title)
.setArtist(track.song.artist)
.setAlbumTitle(track.song.album)
.setExtras(
Bundle().apply { putDouble(GAIN_DB_KEY, track.gainDb ?: 0.0) },
)
.apply {
val bytes = track.artworkBytes
if (bytes != null && bytes.isNotEmpty()) {
setArtworkData(bytes, MediaMetadata.PICTURE_TYPE_FRONT_COVER)
} else if (!track.artworkUri.isNullOrBlank()) {
setArtworkUri(Uri.parse(track.artworkUri))
}
}
.build()
return MediaItem.Builder()
.setUri(uri)
.setMimeType("audio/mpeg")
.setMediaMetadata(metadata)
.build()
}
private fun withController(block: (MediaController) -> Unit) { private fun withController(block: (MediaController) -> Unit) {
val current = controller val current = controller
if (current != null && connected) { if (current != null && connected) {
block(current) block(current)
} else { } else {
// The first playback request can be followed immediately by a seek // The first playback request can be followed immediately by a seek.
// (long-form resume). Keep every action, not only the last one. // Keep every action, not only the last one.
synchronized(pending) { pending.addLast(block) } synchronized(pending) { pending.addLast(block) }
} }
} }
@@ -2,6 +2,8 @@ package win.taptap.musicmanager.client
import android.content.Context import android.content.Context
import android.graphics.BitmapFactory import android.graphics.BitmapFactory
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.graphics.asImageBitmap
import io.ktor.client.engine.HttpClientEngine import io.ktor.client.engine.HttpClientEngine
@@ -21,6 +23,15 @@ actual fun platformStorage(): AppStorage = AndroidStorage(AndroidContextHolder.c
actual fun createAudioPlayer(): AudioPlayer = MediaControllerAudioPlayer(AndroidContextHolder.context) actual fun createAudioPlayer(): AudioPlayer = MediaControllerAudioPlayer(AndroidContextHolder.context)
actual fun isUnmeteredNetwork(): Boolean {
val manager = AndroidContextHolder.context
.getSystemService(ConnectivityManager::class.java) ?: return true
val network = manager.activeNetwork ?: return false
val capabilities = manager.getNetworkCapabilities(network) ?: return false
return capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) &&
capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)
}
class AndroidStorage(context: Context) : AppStorage { class AndroidStorage(context: Context) : AppStorage {
private val root = File(context.filesDir, "audiomanager").apply { mkdirs() } private val root = File(context.filesDir, "audiomanager").apply { mkdirs() }
@@ -1,27 +0,0 @@
package win.taptap.musicmanager.client
/**
* Bridge between the media session in [PlaybackService] and the queue that
* lives in the app's store. Media3 sends headset/Bluetooth next and previous
* here instead of seeking the single-item ExoPlayer.
*/
internal object PlaybackCommands {
@Volatile
var onNext: (() -> Unit)? = null
@Volatile
var onPrevious: (() -> Unit)? = null
/** Returns false when no store is attached, so the default handling applies. */
fun next(): Boolean {
val handler = onNext ?: return false
handler()
return true
}
fun previous(): Boolean {
val handler = onPrevious ?: return false
handler()
return true
}
}
@@ -5,10 +5,11 @@ import android.content.Intent
import android.os.Bundle import android.os.Bundle
import android.os.Handler import android.os.Handler
import android.os.Looper import android.os.Looper
import android.view.KeyEvent
import androidx.core.content.IntentCompat
import androidx.media3.common.AudioAttributes import androidx.media3.common.AudioAttributes
import androidx.media3.common.C import androidx.media3.common.C
import androidx.media3.common.ForwardingPlayer
import androidx.media3.common.MediaItem
import androidx.media3.common.Player
import androidx.media3.exoplayer.ExoPlayer import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.session.MediaSession import androidx.media3.session.MediaSession
import androidx.media3.session.MediaSessionService import androidx.media3.session.MediaSessionService
@@ -22,12 +23,22 @@ internal const val SLEEP_TIMER_ACTION = "win.taptap.musicmanager.client.SLEEP_TI
internal const val SLEEP_TIMER_SECONDS = "seconds" internal const val SLEEP_TIMER_SECONDS = "seconds"
internal val SLEEP_TIMER_COMMAND = SessionCommand(SLEEP_TIMER_ACTION, Bundle.EMPTY) internal val SLEEP_TIMER_COMMAND = SessionCommand(SLEEP_TIMER_ACTION, Bundle.EMPTY)
/** Custom session command that sets the crossfade/fade length. */
internal const val CROSSFADE_ACTION = "win.taptap.musicmanager.client.CROSSFADE"
internal const val CROSSFADE_SECONDS = "seconds"
internal val CROSSFADE_COMMAND = SessionCommand(CROSSFADE_ACTION, Bundle.EMPTY)
/** MediaItem metadata key carrying the server-measured gain in dB. */
internal const val GAIN_DB_KEY = "gainDb"
/** /**
* Hosts playback in a foreground service so audio continues when the activity * Hosts playback in a foreground service so audio continues when the activity
* is backgrounded, the screen is off, or the task is swiped away. * is backgrounded, the screen is off, or the task is swiped away.
* *
* Media3 publishes the media notification and exposes the session to lock-screen * The queue lives here as a Media3 timeline. That lets the notification,
* controls, Bluetooth/headset buttons and Android Auto. * headset buttons and Android Auto advance tracks even when the UI process is
* gone, and makes gapless playback possible because ExoPlayer prepares the next
* item ahead of time.
*/ */
class PlaybackService : MediaSessionService() { class PlaybackService : MediaSessionService() {
@@ -35,10 +46,42 @@ class PlaybackService : MediaSessionService() {
private val handler = Handler(Looper.getMainLooper()) private val handler = Handler(Looper.getMainLooper())
private val sleepTimer = Runnable { mediaSession?.player?.pause() } private val sleepTimer = Runnable { mediaSession?.player?.pause() }
@Volatile private var crossfadeSeconds = 0
@Volatile private var fade = 1f
private val gainProcessor = GainAudioProcessor()
private var player: ExoPlayer? = null
private val fadeLoop = object : Runnable {
override fun run() {
val exo = player ?: return
if (!exo.isPlaying) {
handler.postDelayed(this, FADE_TICK_MS)
return
}
val fadeMs = crossfadeSeconds * 1_000L
if (fadeMs > 0) {
val position = exo.currentPosition.coerceAtLeast(0L)
val duration = exo.duration
val fadeOut = if (duration > 0) {
((duration - position).toFloat() / fadeMs).coerceIn(0f, 1f)
} else {
1f
}
val fadeIn = (position.toFloat() / fadeMs).coerceIn(0f, 1f)
fade = minOf(fadeOut, fadeIn)
} else {
fade = 1f
}
exo.volume = fade.coerceIn(0f, 1f)
handler.postDelayed(this, FADE_TICK_MS)
}
}
override fun onCreate() { override fun onCreate() {
super.onCreate() super.onCreate()
val player = ExoPlayer.Builder(this) val exoPlayer = ExoPlayer.Builder(this)
.setRenderersFactory(GainRenderersFactory(this, gainProcessor))
.setAudioAttributes( .setAudioAttributes(
AudioAttributes.Builder() AudioAttributes.Builder()
.setUsage(C.USAGE_MEDIA) .setUsage(C.USAGE_MEDIA)
@@ -51,6 +94,47 @@ class PlaybackService : MediaSessionService() {
.apply { .apply {
setWakeMode(C.WAKE_MODE_NETWORK) setWakeMode(C.WAKE_MODE_NETWORK)
} }
player = exoPlayer
// Media3's notification/next/previous map onto the real timeline. The
// only custom rule is Android's usual previous behaviour: after two
// seconds of playback it restarts the current item.
val sessionPlayer = object : ForwardingPlayer(exoPlayer) {
override fun seekToPrevious() {
if (exoPlayer.currentPosition > PREVIOUS_RESTART_MS) {
exoPlayer.seekTo(0)
} else if (exoPlayer.hasPreviousMediaItem()) {
exoPlayer.seekToPreviousMediaItem()
} else {
exoPlayer.seekTo(0)
}
}
override fun seekToPreviousMediaItem() {
if (exoPlayer.currentPosition > PREVIOUS_RESTART_MS) {
exoPlayer.seekTo(0)
} else if (exoPlayer.hasPreviousMediaItem()) {
exoPlayer.seekToPreviousMediaItem()
} else {
exoPlayer.seekTo(0)
}
}
}
exoPlayer.addListener(
object : Player.Listener {
override fun onMediaItemTransition(mediaItem: MediaItem?, reason: Int) {
gainProcessor.gain = gainOf(mediaItem)
fade = if (crossfadeSeconds > 0) 0f else 1f
exoPlayer.volume = fade.coerceIn(0f, 1f)
}
override fun onIsPlayingChanged(isPlaying: Boolean) {
handler.removeCallbacks(fadeLoop)
if (isPlaying) handler.post(fadeLoop)
}
},
)
val sessionActivity = PendingIntent.getActivity( val sessionActivity = PendingIntent.getActivity(
this, this,
@@ -59,7 +143,7 @@ class PlaybackService : MediaSessionService() {
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
) )
mediaSession = MediaSession.Builder(this, player) mediaSession = MediaSession.Builder(this, sessionPlayer)
.setSessionActivity(sessionActivity) .setSessionActivity(sessionActivity)
.setCallback(object : MediaSession.Callback { .setCallback(object : MediaSession.Callback {
override fun onConnect( override fun onConnect(
@@ -69,57 +153,37 @@ class PlaybackService : MediaSessionService() {
val commands = MediaSession.ConnectionResult.DEFAULT_SESSION_AND_LIBRARY_COMMANDS val commands = MediaSession.ConnectionResult.DEFAULT_SESSION_AND_LIBRARY_COMMANDS
.buildUpon() .buildUpon()
.add(SLEEP_TIMER_COMMAND) .add(SLEEP_TIMER_COMMAND)
.add(CROSSFADE_COMMAND)
.build() .build()
return MediaSession.ConnectionResult.AcceptedResultBuilder(session) return MediaSession.ConnectionResult.AcceptedResultBuilder(session)
.setAvailableSessionCommands(commands) .setAvailableSessionCommands(commands)
.build() .build()
} }
/**
* A headset skip must move the app's queue, not seek the one
* item ExoPlayer holds. Returning true consumes the event.
*/
override fun onMediaButtonEvent(
session: MediaSession,
controllerInfo: MediaSession.ControllerInfo,
intent: Intent,
): Boolean {
if (intent.action != Intent.ACTION_MEDIA_BUTTON) return false
val event = IntentCompat.getParcelableExtra(
intent,
Intent.EXTRA_KEY_EVENT,
KeyEvent::class.java,
) ?: return false
return when (event.keyCode) {
KeyEvent.KEYCODE_MEDIA_NEXT -> when (event.action) {
KeyEvent.ACTION_DOWN -> PlaybackCommands.next()
KeyEvent.ACTION_UP -> true
else -> false
}
KeyEvent.KEYCODE_MEDIA_PREVIOUS -> when (event.action) {
KeyEvent.ACTION_DOWN -> PlaybackCommands.previous()
KeyEvent.ACTION_UP -> true
else -> false
}
else -> false
}
}
override fun onCustomCommand( override fun onCustomCommand(
session: MediaSession, session: MediaSession,
controller: MediaSession.ControllerInfo, controller: MediaSession.ControllerInfo,
customCommand: SessionCommand, customCommand: SessionCommand,
args: Bundle, args: Bundle,
): ListenableFuture<SessionResult> { ): ListenableFuture<SessionResult> {
if (customCommand.customAction != SLEEP_TIMER_ACTION) { when (customCommand.customAction) {
return super.onCustomCommand(session, controller, customCommand, args) SLEEP_TIMER_ACTION -> {
} handler.removeCallbacks(sleepTimer)
handler.removeCallbacks(sleepTimer) val seconds = args.getLong(SLEEP_TIMER_SECONDS, 0L)
val seconds = args.getLong(SLEEP_TIMER_SECONDS, 0L) if (seconds > 0) {
if (seconds > 0) { handler.postDelayed(sleepTimer, seconds * 1_000)
handler.postDelayed(sleepTimer, seconds * 1_000) }
}
CROSSFADE_ACTION -> {
crossfadeSeconds = args.getInt(CROSSFADE_SECONDS, 0).coerceAtLeast(0)
fade = if (crossfadeSeconds > 0) 0f else 1f
exoPlayer.volume = fade.coerceIn(0f, 1f)
handler.removeCallbacks(fadeLoop)
if (exoPlayer.isPlaying) handler.post(fadeLoop)
}
else -> return super.onCustomCommand(session, controller, customCommand, args)
} }
return Futures.immediateFuture(SessionResult(SessionResult.RESULT_SUCCESS)) return Futures.immediateFuture(SessionResult(SessionResult.RESULT_SUCCESS))
} }
@@ -127,6 +191,11 @@ class PlaybackService : MediaSessionService() {
.build() .build()
} }
private fun gainOf(item: MediaItem?): Float {
val db = item?.mediaMetadata?.extras?.getDouble(GAIN_DB_KEY, 0.0) ?: 0.0
return GainAudioProcessor.fromDb(db)
}
override fun onGetSession(controllerInfo: MediaSession.ControllerInfo): MediaSession? = override fun onGetSession(controllerInfo: MediaSession.ControllerInfo): MediaSession? =
mediaSession mediaSession
@@ -139,11 +208,18 @@ class PlaybackService : MediaSessionService() {
override fun onDestroy() { override fun onDestroy() {
handler.removeCallbacks(sleepTimer) handler.removeCallbacks(sleepTimer)
handler.removeCallbacks(fadeLoop)
mediaSession?.run { mediaSession?.run {
player.release() player.release()
release() release()
} }
mediaSession = null mediaSession = null
player = null
super.onDestroy() super.onDestroy()
} }
private companion object {
const val PREVIOUS_RESTART_MS = 2_000L
const val FADE_TICK_MS = 100L
}
} }
@@ -16,3 +16,9 @@ expect fun platformStorage(): AppStorage
expect fun createAudioPlayer(): AudioPlayer expect fun createAudioPlayer(): AudioPlayer
expect fun decodeImage(bytes: ByteArray): ImageBitmap? expect fun decodeImage(bytes: ByteArray): ImageBitmap?
/**
* True when bulk downloads may run. Android checks for an unmetered network;
* desktop and web have no metered flag and return true.
*/
expect fun isUnmeteredNetwork(): Boolean
@@ -184,8 +184,7 @@ class ApiClient(private val http: HttpClient) {
}, },
) )
suspend fun preview(moodId: String, limit: Int = 20): List<Song> = suspend fun info(): ServerInfo = get("/info")
get<TracksResponse>("/moods/$moodId/preview?limit=$limit").songs
suspend fun search( suspend fun search(
query: String, query: String,
@@ -45,10 +45,21 @@ data class Song(
val size: Long = 0, val size: Long = 0,
val suffix: String = "mp3", val suffix: String = "mp3",
val thumbnail: String? = null, val thumbnail: String? = null,
/** Server-measured loudness and the gain to apply; null when not analyzed. */
val loudnessLufs: Double? = null,
val gainDb: Double? = null,
) { ) {
val subtitle: String get() = album?.takeIf { it.isNotBlank() } ?: artist val subtitle: String get() = album?.takeIf { it.isNotBlank() } ?: artist
} }
@Serializable
data class ServerInfo(
val defaultSource: String = "deezer",
val deezerQuality: Int = 0,
val loudnessEnabled: Boolean = false,
val loudnessTargetLufs: Double = -16.0,
)
@Serializable @Serializable
data class Mood( data class Mood(
val id: String, val id: String,
@@ -32,6 +32,16 @@ data class CachedState(
} }
} }
/** Client-only preferences that are not part of the server profile. */
@Serializable
data class ClientSettings(
/** Moods kept downloaded on this device and auto-synced. */
val offlineMoods: Set<String> = emptySet(),
val normalizationEnabled: Boolean = true,
/** 0 = gapless; other values are fade lengths in seconds. */
val crossfadeSeconds: Int = 0,
)
/** The queue survives a restart so the next launch can resume where it stopped. */ /** The queue survives a restart so the next launch can resume where it stopped. */
@Serializable @Serializable
data class PlaybackSnapshot( data class PlaybackSnapshot(
@@ -70,6 +80,15 @@ class AppCache(private val storage: AppStorage) {
write(CACHE_FILE, json.encodeToString(state)) write(CACHE_FILE, json.encodeToString(state))
} }
fun loadSettings(): ClientSettings =
read(SETTINGS_FILE)?.let {
runCatching { json.decodeFromString<ClientSettings>(it) }.getOrNull()
} ?: ClientSettings()
fun saveSettings(settings: ClientSettings) {
write(SETTINGS_FILE, json.encodeToString(settings))
}
fun loadPlayback(): PlaybackSnapshot? = fun loadPlayback(): PlaybackSnapshot? =
read(PLAYBACK_FILE)?.let { read(PLAYBACK_FILE)?.let {
runCatching { json.decodeFromString<PlaybackSnapshot>(it) }.getOrNull() runCatching { json.decodeFromString<PlaybackSnapshot>(it) }.getOrNull()
@@ -86,6 +105,7 @@ class AppCache(private val storage: AppStorage) {
fun clear() { fun clear() {
delete(CACHE_FILE) delete(CACHE_FILE)
delete(PLAYBACK_FILE) delete(PLAYBACK_FILE)
delete(SETTINGS_FILE)
} }
// Web storage can be blocked (Safari private mode) or full. Cache failure // Web storage can be blocked (Safari private mode) or full. Cache failure
@@ -102,5 +122,6 @@ class AppCache(private val storage: AppStorage) {
const val SESSION_FILE = "session.json" const val SESSION_FILE = "session.json"
const val CACHE_FILE = "mood-cache.json" const val CACHE_FILE = "mood-cache.json"
const val PLAYBACK_FILE = "playback.json" const val PLAYBACK_FILE = "playback.json"
const val SETTINGS_FILE = "settings.json"
} }
} }
@@ -2,20 +2,41 @@ package win.taptap.musicmanager.client.playback
import win.taptap.musicmanager.client.api.Song import win.taptap.musicmanager.client.api.Song
/**
* One entry in the playback timeline. The store resolves the stream or local
* file and holds the metadata the service needs for the notification.
*/
data class PlaybackTrack(
val song: Song,
/** HTTP stream URL or a local file path. */
val source: String,
val local: Boolean,
val artworkUri: String? = null,
/** Cached cover for offline playback; avoids a network fetch in the notification. */
val artworkBytes: ByteArray? = null,
/** Server-measured gain; null leaves the track untouched. */
val gainDb: Double? = null,
)
/** /**
* Minimal audio abstraction shared by all targets. * Minimal audio abstraction shared by all targets.
* *
* `source` is either an HTTP URL (tokenized stream) or a local file handle. The * The timeline is owned by the player so Android's media service can keep
* store polls [isFinished] because some backends have no callback support. * advancing tracks when the UI process is gone. The store mirrors
* [currentIndex] and the song list it last supplied.
*/ */
interface AudioPlayer { interface AudioPlayer {
fun play( /** Replaces the timeline and starts at [startIndex]. */
source: String, fun setQueue(tracks: List<PlaybackTrack>, startIndex: Int, startAtSeconds: Double = 0.0)
song: Song, fun appendToQueue(tracks: List<PlaybackTrack>)
local: Boolean, fun moveInQueue(fromIndex: Int, toIndex: Int)
artworkUri: String? = null, fun removeAt(index: Int)
artworkBytes: ByteArray? = null, fun playIndex(index: Int, startAtSeconds: Double = 0.0)
) fun skipToNext()
fun skipToPrevious(restartAfterSeconds: Double = 2.0)
fun currentIndex(): Int
fun queueSize(): Int
fun pause() fun pause()
fun resume() fun resume()
fun stop() fun stop()
@@ -25,21 +46,17 @@ interface AudioPlayer {
fun durationSeconds(): Double fun durationSeconds(): Double
val canSeek: Boolean val canSeek: Boolean
fun seekTo(seconds: Double) fun seekTo(seconds: Double)
fun release()
/** Crossfade length in seconds; 0 means gapless. Platforms may ignore it. */
fun setCrossfadeSeconds(seconds: Int) = Unit
val supportsCrossfade: Boolean get() = false
/** /**
* Pauses playback after [seconds], or cancels a pending timer with null. * Pauses playback after [seconds], or cancels a pending timer with null.
* Returns true when the platform scheduled the pause itself, so it still * Returns true when the platform scheduled the pause itself, so it still
* fires when the UI is gone (Android background playback). Callers keep * fires when the UI is gone (Android background playback).
* their own countdown for the UI either way.
*/ */
fun scheduleSleepTimer(seconds: Long?): Boolean = false fun scheduleSleepTimer(seconds: Long?): Boolean = false
/** fun release()
* Routes hardware transport buttons (headset/Bluetooth next and previous)
* to the app's own queue. Android wires this to its MediaSession; other
* platforms ignore it. Null clears the handlers.
*/
fun setSkipCallbacks(onNext: (() -> Unit)?, onPrevious: (() -> Unit)?) = Unit
} }
File diff suppressed because it is too large. Load diff
@@ -103,7 +103,6 @@ private fun Splash() {
@Composable @Composable
private fun MainScreen(state: AppState, store: AppStore) { private fun MainScreen(state: AppState, store: AppStore) {
val snackbar = remember { SnackbarHostState() } val snackbar = remember { SnackbarHostState() }
var confirmDelete by remember { mutableStateOf(false) }
LaunchedEffect(state.messageId) { LaunchedEffect(state.messageId) {
val message = state.message val message = state.message
@@ -114,7 +113,7 @@ private fun MainScreen(state: AppState, store: AppStore) {
} }
PlatformBackHandler(enabled = state.screen != Screen.Moods) { PlatformBackHandler(enabled = state.screen != Screen.Moods) {
store.openMoods() store.back()
} }
Scaffold( Scaffold(
@@ -127,7 +126,7 @@ private fun MainScreen(state: AppState, store: AppStore) {
), ),
navigationIcon = { navigationIcon = {
if (state.screen != Screen.Moods) { if (state.screen != Screen.Moods) {
IconButton(onClick = { store.openMoods() }) { IconButton(onClick = { store.back() }) {
Icon(Icons.Rounded.ArrowBack, contentDescription = "Back") Icon(Icons.Rounded.ArrowBack, contentDescription = "Back")
} }
} }
@@ -137,9 +136,11 @@ private fun MainScreen(state: AppState, store: AppStore) {
val title = when (state.screen) { val title = when (state.screen) {
Screen.Moods -> "Moods" Screen.Moods -> "Moods"
Screen.MoodDetail -> state.selectedMood?.mood?.name ?: "Mood" Screen.MoodDetail -> state.selectedMood?.mood?.name ?: "Mood"
Screen.MoodSettings -> "Mood settings"
Screen.Search -> "Add music" Screen.Search -> "Add music"
Screen.Downloads -> "Downloads" Screen.Downloads -> "Downloads"
Screen.Settings -> "Settings" Screen.Settings -> "Settings"
Screen.NowPlaying -> "Now playing"
} }
Text(title, fontWeight = FontWeight.SemiBold) Text(title, fontWeight = FontWeight.SemiBold)
if (state.offline) { if (state.offline) {
@@ -168,11 +169,11 @@ private fun MainScreen(state: AppState, store: AppStore) {
} }
} }
Screen.MoodDetail -> { Screen.MoodDetail -> {
IconButton(onClick = { confirmDelete = true }) { IconButton(onClick = { store.openMoodSettings() }) {
Icon(Icons.Rounded.Delete, contentDescription = "Delete mood") Icon(Icons.Rounded.Settings, contentDescription = "Mood settings")
} }
} }
Screen.Search -> Unit Screen.MoodSettings, Screen.NowPlaying, Screen.Search -> Unit
Screen.Downloads -> { Screen.Downloads -> {
IconButton(onClick = { store.openSettings() }) { IconButton(onClick = { store.openSettings() }) {
Icon(Icons.Rounded.Settings, contentDescription = "Settings") Icon(Icons.Rounded.Settings, contentDescription = "Settings")
@@ -184,7 +185,7 @@ private fun MainScreen(state: AppState, store: AppStore) {
) )
}, },
bottomBar = { bottomBar = {
if (state.current != null) { if (state.current != null && state.screen != Screen.NowPlaying) {
PlayerBar(state, store) PlayerBar(state, store)
} }
}, },
@@ -193,35 +194,12 @@ private fun MainScreen(state: AppState, store: AppStore) {
when (state.screen) { when (state.screen) {
Screen.Moods -> MoodsScreen(state, store) Screen.Moods -> MoodsScreen(state, store)
Screen.MoodDetail -> MoodDetailScreen(state, store) Screen.MoodDetail -> MoodDetailScreen(state, store)
Screen.MoodSettings -> MoodSettingsScreen(state, store)
Screen.Search -> SearchScreen(state, store) Screen.Search -> SearchScreen(state, store)
Screen.Downloads -> DownloadsScreen(state, store) Screen.Downloads -> DownloadsScreen(state, store)
Screen.Settings -> SettingsScreen(state, store) Screen.Settings -> SettingsScreen(state, store)
Screen.NowPlaying -> NowPlayingScreen(state, store)
} }
} }
} }
if (confirmDelete) {
val name = state.selectedMood?.mood?.name ?: "this mood"
AlertDialog(
onDismissRequest = { confirmDelete = false },
title = { Text("Delete mood?") },
text = {
Text(
"\"$name\" and its recommendation history will be removed. " +
"Unused downloads are deleted from the server.",
)
},
confirmButton = {
TextButton(
onClick = {
confirmDelete = false
state.selectedMood?.let { store.deleteMood(it.mood.id) }
},
) { Text("Delete", color = MaterialTheme.colorScheme.error) }
},
dismissButton = {
TextButton(onClick = { confirmDelete = false }) { Text("Cancel") }
},
)
}
} }
@@ -24,6 +24,7 @@ import androidx.compose.material.icons.rounded.PlayArrow
import androidx.compose.material.icons.rounded.Refresh import androidx.compose.material.icons.rounded.Refresh
import androidx.compose.material.icons.rounded.RemoveCircleOutline import androidx.compose.material.icons.rounded.RemoveCircleOutline
import androidx.compose.material.icons.rounded.Search import androidx.compose.material.icons.rounded.Search
import androidx.compose.material.icons.rounded.Settings
import androidx.compose.material3.Button import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenu
@@ -78,15 +79,6 @@ fun MoodDetailScreen(state: AppState, store: AppStore) {
} }
val mood = detail.mood val mood = detail.mood
var name by remember(mood.id) { mutableStateOf(mood.name) }
var description by remember(mood.id) { mutableStateOf(mood.description.orEmpty()) }
var genres by remember(mood.id) { mutableStateOf(mood.genres.joinToString(", ")) }
var query by remember(mood.id) { mutableStateOf(mood.query.orEmpty()) }
var source by remember(mood.id) { mutableStateOf(mood.source) }
var sourceMenu by remember { mutableStateOf(false) }
var collectionPercent by remember(mood.id) { mutableStateOf(mood.collectionPercent.toFloat()) }
var recommendations by remember(mood.id) { mutableStateOf(mood.recommendationCount.toFloat()) }
var hours by remember(mood.id) { mutableStateOf(mood.refreshHours.toString()) }
val inFlight = mood.recommendationDownloading + val inFlight = mood.recommendationDownloading +
detail.recommendations.count { detail.recommendations.count {
@@ -183,24 +175,10 @@ fun MoodDetailScreen(state: AppState, store: AppStore) {
Spacer(Modifier.width(6.dp)) Spacer(Modifier.width(6.dp))
Text("Add music") Text("Add music")
} }
} OutlinedButton(onClick = { store.openMoodSettings() }) {
} Icon(Icons.Rounded.Settings, contentDescription = null, modifier = Modifier.size(18.dp))
Spacer(Modifier.width(6.dp))
if (state.preview.isNotEmpty()) { Text("Settings")
item {
HorizontalDivider(Modifier.padding(vertical = 12.dp))
SectionTitle("Next batch")
Text(
"What the radio would play next, mixed from this mood and its ready picks. " +
"Nothing here is downloaded or saved.",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Spacer(Modifier.height(4.dp))
}
items(state.preview, key = { "preview-${it.id}" }) { song ->
SongRow(store, song, onPlay = { store.playSong(song) }) {
Text(formatDuration(song.duration), style = MaterialTheme.typography.labelSmall)
} }
} }
} }
@@ -251,144 +229,8 @@ fun MoodDetailScreen(state: AppState, store: AppStore) {
} }
} }
item {
HorizontalDivider(Modifier.padding(vertical = 12.dp))
SectionTitle("Settings")
}
item {
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
OutlinedTextField(
value = name,
onValueChange = { name = it },
label = { Text("Name") },
singleLine = true,
modifier = Modifier.fillMaxWidth(),
)
OutlinedTextField(
value = description,
onValueChange = { description = it },
label = { Text("Description") },
singleLine = true,
modifier = Modifier.fillMaxWidth(),
)
OutlinedTextField(
value = genres,
onValueChange = { genres = it },
label = { Text("Genres (comma separated)") },
singleLine = true,
modifier = Modifier.fillMaxWidth(),
)
OutlinedTextField(
value = query,
onValueChange = { query = it },
label = { Text("Discovery hint") },
singleLine = true,
modifier = Modifier.fillMaxWidth(),
)
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
) {
Column(Modifier.weight(1f)) {
Text("Download source", style = MaterialTheme.typography.bodyMedium)
Text(
"Search, recommendations and downloads use this catalog.",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
Box {
OutlinedButton(onClick = { sourceMenu = true }) {
Text(sourceLabel(source))
}
DropdownMenu(
expanded = sourceMenu,
onDismissRequest = { sourceMenu = false },
) {
listOf("deezer", "youtube").forEach { option ->
DropdownMenuItem(
text = { Text(sourceLabel(option)) },
onClick = {
sourceMenu = false
source = option
},
)
}
}
}
}
if (source != mood.source) {
Text(
"Changing the source clears active recommendations and refills them.",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.tertiary,
)
}
Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
Text(
"Collection share: ${collectionPercent.roundToInt()}% · ${100 - collectionPercent.roundToInt()}% recommendations",
style = MaterialTheme.typography.bodySmall,
)
Slider(
value = collectionPercent,
onValueChange = { collectionPercent = it },
valueRange = 0f..100f,
steps = 9,
)
Text(
"Each queue slot rolls this share; when one pool runs out the other fills in.",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
Text(
"Active recommendations: ${recommendations.roundToInt()}",
style = MaterialTheme.typography.bodySmall,
)
Slider(
value = recommendations,
onValueChange = { recommendations = it },
valueRange = 0f..30f,
steps = 29,
)
Text(
"Downloaded picks that count as active slots (0 turns discovery off).",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
OutlinedTextField(
value = hours,
onValueChange = { hours = it },
label = { Text("Refresh interval (hours)") },
singleLine = true,
modifier = Modifier.fillMaxWidth(),
)
FilledTonalButton(
enabled = !state.saving && name.isNotBlank(),
onClick = {
store.saveMood(
detail = detail,
name = name.trim(),
description = description.trim().takeIf { it.isNotEmpty() },
genres = genres.split(',').map { it.trim() }.filter { it.isNotEmpty() },
query = query.trim().takeIf { it.isNotEmpty() },
source = source,
collectionPercent = collectionPercent.roundToInt(),
recommendationCount = recommendations.roundToInt(),
refreshHours = hours.toIntOrNull() ?: mood.refreshHours,
)
},
modifier = Modifier.fillMaxWidth(),
) {
Text(if (state.saving) "Saving..." else "Save settings")
}
}
}
item { Spacer(Modifier.size(24.dp)) } item { Spacer(Modifier.size(24.dp)) }
} }
} }
@@ -0,0 +1,354 @@
package win.taptap.musicmanager.client.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Delete
import androidx.compose.material.icons.rounded.DownloadDone
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Slider
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import kotlin.math.roundToInt
import win.taptap.musicmanager.client.store.AppState
import win.taptap.musicmanager.client.store.AppStore
import win.taptap.musicmanager.client.store.sourceLabel
/**
* Dedicated mood settings screen. Keeping the form out of the mood page makes
* the collection the focus and gives destructive actions their own place at the
* bottom instead of the top bar.
*/
@Composable
fun MoodSettingsScreen(state: AppState, store: AppStore) {
val detail = state.selectedMood
if (detail == null) {
EmptyState("Mood not available", "Open a mood first.")
return
}
val mood = detail.mood
var name by remember(mood.id) { mutableStateOf(mood.name) }
var description by remember(mood.id) { mutableStateOf(mood.description.orEmpty()) }
var genres by remember(mood.id) { mutableStateOf(mood.genres.joinToString(", ")) }
var query by remember(mood.id) { mutableStateOf(mood.query.orEmpty()) }
var source by remember(mood.id) { mutableStateOf(mood.source) }
var sourceMenu by remember { mutableStateOf(false) }
var collectionPercent by remember(mood.id) { mutableStateOf(mood.collectionPercent.toFloat()) }
var recommendations by remember(mood.id) { mutableStateOf(mood.recommendationCount.toFloat()) }
var hours by remember(mood.id) { mutableStateOf(mood.refreshHours.toString()) }
var confirmDelete by remember { mutableStateOf(false) }
val offline = mood.id in state.offlineMoods
val offlineDownloaded = detail.songs.count { it.song.id in state.downloads }
LazyColumn(
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(20.dp),
verticalArrangement = Arrangement.spacedBy(12.dp),
) {
item {
Surface(
shape = RoundedCornerShape(18.dp),
color = MaterialTheme.colorScheme.surfaceVariant,
modifier = Modifier.fillMaxWidth(),
) {
Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
Text(
mood.name,
style = MaterialTheme.typography.titleLarge,
fontWeight = FontWeight.SemiBold,
)
Text(
"${mood.songCount} songs · ${mood.collectionPercent}% collection",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
item {
SectionTitle("Details")
}
item {
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
OutlinedTextField(
value = name,
onValueChange = { name = it },
label = { Text("Name") },
singleLine = true,
modifier = Modifier.fillMaxWidth(),
)
OutlinedTextField(
value = description,
onValueChange = { description = it },
label = { Text("Description") },
singleLine = true,
modifier = Modifier.fillMaxWidth(),
)
OutlinedTextField(
value = genres,
onValueChange = { genres = it },
label = { Text("Genres (comma separated)") },
singleLine = true,
modifier = Modifier.fillMaxWidth(),
)
OutlinedTextField(
value = query,
onValueChange = { query = it },
label = { Text("Discovery hint") },
singleLine = true,
modifier = Modifier.fillMaxWidth(),
)
}
}
item {
SectionTitle("Downloads")
}
item {
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
) {
Column(Modifier.weight(1f)) {
Text("Download source", style = MaterialTheme.typography.bodyMedium)
Text(
"Search, recommendations and downloads use this catalog.",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
Box {
OutlinedButton(onClick = { sourceMenu = true }) {
Text(sourceLabel(source))
}
DropdownMenu(
expanded = sourceMenu,
onDismissRequest = { sourceMenu = false },
) {
listOf("deezer", "youtube").forEach { option ->
DropdownMenuItem(
text = { Text(sourceLabel(option)) },
onClick = {
sourceMenu = false
source = option
},
)
}
}
}
}
if (source != mood.source) {
Text(
"Changing the source clears active recommendations and refills them.",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.tertiary,
)
}
HorizontalDivider()
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
) {
Column(Modifier.weight(1f)) {
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(
Icons.Rounded.DownloadDone,
contentDescription = null,
modifier = Modifier.size(18.dp),
tint = MaterialTheme.colorScheme.primary,
)
Spacer(Modifier.width(6.dp))
Text("Keep this mood offline", style = MaterialTheme.typography.bodyMedium)
}
Text(
if (offline) {
"$offlineDownloaded of ${detail.songs.size} downloaded · " +
"new songs sync on Wi-Fi"
} else {
"Downloads every song and keeps new additions in sync on Wi-Fi."
},
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
Switch(
checked = offline,
onCheckedChange = { store.setMoodOffline(mood.id, it) },
)
}
}
}
item {
SectionTitle("Mixing")
}
item {
Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
Text(
"Collection share: ${collectionPercent.roundToInt()}% · " +
"${100 - collectionPercent.roundToInt()}% recommendations",
style = MaterialTheme.typography.bodySmall,
)
Slider(
value = collectionPercent,
onValueChange = { collectionPercent = it },
valueRange = 0f..100f,
steps = 9,
)
Text(
"Each queue slot rolls this share; when one pool runs out the other fills in.",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
item {
Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
Text(
"Active recommendations: ${recommendations.roundToInt()}",
style = MaterialTheme.typography.bodySmall,
)
Slider(
value = recommendations,
onValueChange = { recommendations = it },
valueRange = 0f..30f,
steps = 29,
)
Text(
"Downloaded picks that count as active slots (0 turns discovery off).",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
item {
OutlinedTextField(
value = hours,
onValueChange = { hours = it },
label = { Text("Refresh interval (hours)") },
singleLine = true,
modifier = Modifier.fillMaxWidth(),
)
}
item {
FilledTonalButton(
enabled = !state.saving && name.isNotBlank(),
onClick = {
store.saveMood(
detail = detail,
name = name.trim(),
description = description.trim().takeIf { it.isNotEmpty() },
genres = genres.split(',').map { it.trim() }.filter { it.isNotEmpty() },
query = query.trim().takeIf { it.isNotEmpty() },
source = source,
collectionPercent = collectionPercent.roundToInt(),
recommendationCount = recommendations.roundToInt(),
refreshHours = hours.toIntOrNull() ?: mood.refreshHours,
)
},
modifier = Modifier.fillMaxWidth(),
) {
if (state.saving) {
CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp)
Spacer(Modifier.width(8.dp))
}
Text(if (state.saving) "Saving..." else "Save settings")
}
}
item {
Spacer(Modifier.height(24.dp))
HorizontalDivider()
Spacer(Modifier.height(16.dp))
Text(
"Deleting a mood removes it for everyone who can see it. Downloaded files " +
"shared with other moods are kept.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Spacer(Modifier.height(10.dp))
Button(
onClick = { confirmDelete = true },
colors = ButtonDefaults.buttonColors(
containerColor = MaterialTheme.colorScheme.errorContainer,
contentColor = MaterialTheme.colorScheme.onErrorContainer,
),
modifier = Modifier.fillMaxWidth(),
) {
Icon(Icons.Rounded.Delete, contentDescription = null, modifier = Modifier.size(18.dp))
Spacer(Modifier.width(8.dp))
Text("Delete mood")
}
}
}
if (confirmDelete) {
AlertDialog(
onDismissRequest = { confirmDelete = false },
title = { Text("Delete \"${mood.name}\"?") },
text = {
Text(
"This cannot be undone. Downloaded tracks stay available to other moods " +
"that still use them.",
)
},
confirmButton = {
TextButton(
onClick = {
confirmDelete = false
store.deleteMood(mood.id)
},
) {
Text("Delete", color = MaterialTheme.colorScheme.error)
}
},
dismissButton = {
TextButton(onClick = { confirmDelete = false }) { Text("Cancel") }
},
)
}
}
@@ -0,0 +1,353 @@
package win.taptap.musicmanager.client.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Bedtime
import androidx.compose.material.icons.rounded.DownloadDone
import androidx.compose.material.icons.rounded.Pause
import androidx.compose.material.icons.rounded.PlayArrow
import androidx.compose.material.icons.rounded.PlaylistAdd
import androidx.compose.material.icons.rounded.QueueMusic
import androidx.compose.material.icons.rounded.SkipNext
import androidx.compose.material.icons.rounded.SkipPrevious
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Slider
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import win.taptap.musicmanager.client.store.AppState
import win.taptap.musicmanager.client.store.AppStore
import win.taptap.musicmanager.client.store.sourceLabel
/**
* Full-screen player. The compact bar stays visible on other screens; tapping
* it opens this view with large artwork, the timeline, transport, offline and
* mood actions, and the upcoming queue.
*/
@Composable
fun NowPlayingScreen(state: AppState, store: AppStore) {
val song = state.current
if (song == null) {
EmptyState("Nothing playing", "Pick a mood and press play.", Modifier.fillMaxSize())
return
}
var sleepMenu by remember { mutableStateOf(false) }
var queueOpen by remember { mutableStateOf(false) }
var picker by remember { mutableStateOf(false) }
var dragSeconds by remember(song.id) { mutableStateOf<Float?>(null) }
val progress = if (state.durationSeconds > 0) {
(state.positionSeconds / state.durationSeconds).toFloat().coerceIn(0f, 1f)
} else {
0f
}
val quality = buildString {
append(sourceLabel(song.source))
if (song.bitRate > 0) {
append(" · ")
append(song.bitRate)
append(" kbps")
}
if (song.id in state.downloads) append(" · offline")
}
LazyColumn(
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(24.dp),
verticalArrangement = Arrangement.spacedBy(16.dp),
) {
item {
Cover(
store = store,
songId = song.id,
modifier = Modifier
.fillMaxWidth()
.aspectRatio(1f)
.padding(horizontal = 12.dp),
size = 800,
)
}
item {
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
Text(
song.title,
style = MaterialTheme.typography.headlineSmall,
fontWeight = FontWeight.Bold,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
)
Text(
song.artist,
style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
Text(
quality,
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary,
)
}
}
item {
Column {
Slider(
value = dragSeconds ?: progress,
onValueChange = { dragSeconds = it },
onValueChangeFinished = {
dragSeconds?.let { fraction ->
if (state.durationSeconds > 0) {
store.seekTo(fraction * state.durationSeconds)
}
}
dragSeconds = null
},
enabled = store.canSeek() && state.durationSeconds > 0,
)
Row(Modifier.fillMaxWidth()) {
Text(
formatDuration(state.positionSeconds.toInt()),
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Spacer(Modifier.weight(1f))
Text(
formatDuration(state.durationSeconds.toInt()),
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
item {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceEvenly,
) {
IconButton(onClick = { store.previous() }, modifier = Modifier.size(52.dp)) {
Icon(
Icons.Rounded.SkipPrevious,
contentDescription = "Previous",
modifier = Modifier.size(36.dp),
)
}
IconButton(onClick = { store.togglePlayPause() }, modifier = Modifier.size(76.dp)) {
Icon(
if (state.playing) Icons.Rounded.Pause else Icons.Rounded.PlayArrow,
contentDescription = if (state.playing) "Pause" else "Play",
modifier = Modifier.size(52.dp),
)
}
IconButton(onClick = { store.skip() }, modifier = Modifier.size(52.dp)) {
Icon(
Icons.Rounded.SkipNext,
contentDescription = "Skip",
modifier = Modifier.size(36.dp),
)
}
}
}
item {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
FilledTonalButton(
onClick = {
if (state.session != null) {
store.addCurrentToMood(null)
} else {
picker = true
}
},
modifier = Modifier.weight(1f),
) {
Icon(Icons.Rounded.PlaylistAdd, contentDescription = null, modifier = Modifier.size(18.dp))
Spacer(Modifier.width(6.dp))
Text("Add to mood")
}
IconButton(onClick = { queueOpen = true }) {
Icon(Icons.Rounded.QueueMusic, contentDescription = "Queue")
}
androidx.compose.foundation.layout.Box {
IconButton(onClick = { sleepMenu = true }) {
Icon(
Icons.Rounded.Bedtime,
contentDescription = "Sleep timer",
tint = if (state.sleepTimerRemainingSeconds != null || state.sleepAtTrackEnd) {
MaterialTheme.colorScheme.primary
} else {
MaterialTheme.colorScheme.onSurfaceVariant
},
)
}
SleepTimerMenu(
expanded = sleepMenu,
onDismiss = { sleepMenu = false },
state = state,
store = store,
)
}
}
}
if (state.sleepAtTrackEnd) {
item {
Text(
"Sleep: stopping after this track",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary,
)
}
} else if (state.sleepTimerRemainingSeconds != null) {
item {
Text(
"Sleep in ${formatDuration(state.sleepTimerRemainingSeconds.toInt())}",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary,
)
}
}
if (song.id in state.downloads) {
item {
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(
Icons.Rounded.DownloadDone,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(18.dp),
)
Spacer(Modifier.width(6.dp))
Text(
"Available without the server",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
item {
HorizontalDivider()
SectionTitle("Up next") {
Text(
"${state.queue.size}",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
if (state.queue.isEmpty()) {
item {
Text(
"Nothing queued. The radio adds tracks automatically.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
} else {
itemsIndexed(
state.queue.take(10),
key = { _, item -> "np-${item.id}" },
) { index, queued ->
SongRow(
store = store,
song = queued,
onPlay = { store.playFromQueue(index) },
) {
Text(
formatDuration(queued.duration),
style = MaterialTheme.typography.labelSmall,
)
}
}
}
}
if (queueOpen) QueueDialog(state, store) { queueOpen = false }
if (picker) {
MoodPickerDialog(
moods = state.moods,
currentMoodId = state.session?.moodId,
onDismiss = { picker = false },
onSelect = { mood ->
picker = false
store.addCurrentToMood(mood.id)
},
)
}
}
@Composable
internal fun SleepTimerMenu(
expanded: Boolean,
onDismiss: () -> Unit,
state: AppState,
store: AppStore,
) {
DropdownMenu(expanded = expanded, onDismissRequest = onDismiss) {
DropdownMenuItem(
text = { Text("Finish this track") },
onClick = {
onDismiss()
store.setSleepAfterTrack()
},
)
listOf(15, 30, 45, 60, 90).forEach { minutes ->
DropdownMenuItem(
text = { Text("$minutes minutes") },
onClick = {
onDismiss()
store.setSleepTimer(minutes)
},
)
}
if (state.sleepTimerRemainingSeconds != null || state.sleepAtTrackEnd) {
HorizontalDivider()
DropdownMenuItem(
text = { Text("Turn off") },
onClick = {
onDismiss()
store.setSleepTimer(null)
},
)
}
}
}
@@ -1,6 +1,7 @@
package win.taptap.musicmanager.client.ui package win.taptap.musicmanager.client.ui
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectDragGesturesAfterLongPress import androidx.compose.foundation.gestures.detectDragGesturesAfterLongPress
import androidx.compose.foundation.gestures.scrollBy import androidx.compose.foundation.gestures.scrollBy
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
@@ -102,6 +103,17 @@ fun PlayerBar(state: AppState, store: AppStore) {
enabled = store.canSeek() && state.durationSeconds > 0, enabled = store.canSeek() && state.durationSeconds > 0,
modifier = Modifier.weight(1f), modifier = Modifier.weight(1f),
) )
IconButton(
onClick = {
if (state.session != null) {
store.addCurrentToMood(null)
} else {
picker = true
}
},
) {
Icon(Icons.Rounded.PlaylistAdd, contentDescription = "Add to mood")
}
IconButton(onClick = { queueOpen = true }) { IconButton(onClick = { queueOpen = true }) {
Icon(Icons.Rounded.QueueMusic, contentDescription = "Queue") Icon(Icons.Rounded.QueueMusic, contentDescription = "Queue")
} }
@@ -113,16 +125,6 @@ fun PlayerBar(state: AppState, store: AppStore) {
expanded = moreMenu, expanded = moreMenu,
onDismissRequest = { moreMenu = false }, onDismissRequest = { moreMenu = false },
) { ) {
DropdownMenuItem(
text = { Text("Add to current mood") },
leadingIcon = {
Icon(Icons.Rounded.AddCircleOutline, contentDescription = null)
},
onClick = {
moreMenu = false
store.addCurrentToMood(null)
},
)
DropdownMenuItem( DropdownMenuItem(
text = { Text("Add to another mood") }, text = { Text("Add to another mood") },
leadingIcon = { leadingIcon = {
@@ -140,37 +142,19 @@ fun PlayerBar(state: AppState, store: AppStore) {
Icon( Icon(
Icons.Rounded.Bedtime, Icons.Rounded.Bedtime,
contentDescription = "Sleep timer", contentDescription = "Sleep timer",
tint = if (sleepRemaining != null) { tint = if (sleepRemaining != null || state.sleepAtTrackEnd) {
MaterialTheme.colorScheme.primary MaterialTheme.colorScheme.primary
} else { } else {
MaterialTheme.colorScheme.onSurfaceVariant MaterialTheme.colorScheme.onSurfaceVariant
}, },
) )
} }
DropdownMenu( SleepTimerMenu(
expanded = sleepMenu, expanded = sleepMenu,
onDismissRequest = { sleepMenu = false }, onDismiss = { sleepMenu = false },
) { state = state,
listOf(15, 30, 45, 60, 90).forEach { minutes -> store = store,
DropdownMenuItem( )
text = { Text("$minutes minutes") },
onClick = {
sleepMenu = false
store.setSleepTimer(minutes)
},
)
}
if (sleepRemaining != null) {
HorizontalDivider()
DropdownMenuItem(
text = { Text("Turn off") },
onClick = {
sleepMenu = false
store.setSleepTimer(null)
},
)
}
}
} }
} }
@@ -181,6 +165,13 @@ fun PlayerBar(state: AppState, store: AppStore) {
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(6.dp), horizontalArrangement = Arrangement.spacedBy(6.dp),
) { ) {
Row(
modifier = Modifier
.weight(1f)
.clickable(onClick = { store.openNowPlaying() }),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(10.dp),
) {
Cover(store, song.id, Modifier.size(48.dp), size = 160) Cover(store, song.id, Modifier.size(48.dp), size = 160)
Column(Modifier.weight(1f)) { Column(Modifier.weight(1f)) {
Text( Text(
@@ -201,7 +192,9 @@ fun PlayerBar(state: AppState, store: AppStore) {
append(formatDuration(state.positionSeconds.toInt())) append(formatDuration(state.positionSeconds.toInt()))
append(" / ") append(" / ")
append(formatDuration(state.durationSeconds.toInt())) append(formatDuration(state.durationSeconds.toInt()))
if (sleepRemaining != null) { if (state.sleepAtTrackEnd) {
append(" · sleep after track")
} else if (sleepRemaining != null) {
append(" · sleep ") append(" · sleep ")
append(formatDuration(sleepRemaining.toInt())) append(formatDuration(sleepRemaining.toInt()))
} }
@@ -212,6 +205,7 @@ fun PlayerBar(state: AppState, store: AppStore) {
overflow = TextOverflow.Ellipsis, overflow = TextOverflow.Ellipsis,
) )
} }
}
IconButton( IconButton(
onClick = { store.previous() }, onClick = { store.previous() },
@@ -265,7 +259,7 @@ fun PlayerBar(state: AppState, store: AppStore) {
} }
@Composable @Composable
private fun QueueDialog(state: AppState, store: AppStore, onDismiss: () -> Unit) { fun QueueDialog(state: AppState, store: AppStore, onDismiss: () -> Unit) {
val listState = rememberLazyListState() val listState = rememberLazyListState()
var draggingIndex by remember { mutableStateOf<Int?>(null) } var draggingIndex by remember { mutableStateOf<Int?>(null) }
var dragPointerY by remember { mutableStateOf(0f) } var dragPointerY by remember { mutableStateOf(0f) }
@@ -20,13 +20,16 @@ import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Slider
import androidx.compose.material3.Surface import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import kotlin.math.roundToInt
import win.taptap.musicmanager.client.platformName import win.taptap.musicmanager.client.platformName
import win.taptap.musicmanager.client.store.AppState import win.taptap.musicmanager.client.store.AppState
import win.taptap.musicmanager.client.store.AppStore import win.taptap.musicmanager.client.store.AppStore
@@ -66,6 +69,78 @@ fun SettingsScreen(state: AppState, store: AppStore) {
} }
} }
item {
val info = state.serverInfo
Surface(
shape = RoundedCornerShape(16.dp),
color = MaterialTheme.colorScheme.surfaceVariant,
modifier = Modifier.fillMaxWidth(),
) {
Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
Text("Audio", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
Row(verticalAlignment = Alignment.CenterVertically) {
Column(Modifier.weight(1f)) {
Text("Loudness normalization", style = MaterialTheme.typography.bodyMedium)
Text(
when {
info == null -> "The server does not report audio settings."
info.loudnessEnabled ->
"Server-measured gain per track, target ${info.loudnessTargetLufs} LUFS."
else -> "Disabled on this server."
},
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
Switch(
checked = state.normalizationEnabled && info?.loudnessEnabled == true,
onCheckedChange = { store.setNormalizationEnabled(it) },
enabled = info?.loudnessEnabled == true,
)
}
if (store.supportsCrossfade()) {
Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
Text(
if (state.crossfadeSeconds == 0) {
"Track transition: gapless"
} else {
"Track transition: ${state.crossfadeSeconds}s fade"
},
style = MaterialTheme.typography.bodyMedium,
)
Slider(
value = state.crossfadeSeconds.toFloat(),
onValueChange = { store.setCrossfadeSeconds(it.roundToInt()) },
valueRange = 0f..8f,
steps = 7,
)
}
}
info?.let {
Text(
buildString {
append(if (it.defaultSource == "deezer") "Deezer" else "YouTube Music")
append(" default · ")
if (it.defaultSource == "deezer") {
append(
if (it.deezerQuality == 1) {
"320 kbps downloads"
} else {
"128 kbps downloads (320 needs a Premium/HiFi ARL)"
},
)
} else {
append("best available audio")
}
},
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
}
item { item {
Surface( Surface(
shape = RoundedCornerShape(16.dp), shape = RoundedCornerShape(16.dp),
@@ -79,6 +154,17 @@ fun SettingsScreen(state: AppState, store: AppStore) {
style = MaterialTheme.typography.bodySmall, style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
) )
Text(
if (state.offlineMoods.isEmpty()) {
"No mood is kept offline."
} else {
"${state.offlineMoods.size} mood(s) auto-sync on Wi-Fi: " +
state.moods.filter { it.id in state.offlineMoods }
.joinToString(", ") { it.name }
},
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Row( Row(
horizontalArrangement = Arrangement.spacedBy(10.dp), horizontalArrangement = Arrangement.spacedBy(10.dp),
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
@@ -107,7 +193,7 @@ fun SettingsScreen(state: AppState, store: AppStore) {
Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) { Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
Text("About", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) Text("About", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
Text( Text(
"AudioManager 0.3.1 · $platformName", "AudioManager 0.4.2 · $platformName",
style = MaterialTheme.typography.bodySmall, style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant, color = MaterialTheme.colorScheme.onSurfaceVariant,
) )
@@ -29,6 +29,7 @@ import win.taptap.musicmanager.client.data.CachedState
import win.taptap.musicmanager.client.data.PlaybackSnapshot import win.taptap.musicmanager.client.data.PlaybackSnapshot
import win.taptap.musicmanager.client.data.SessionState import win.taptap.musicmanager.client.data.SessionState
import win.taptap.musicmanager.client.playback.AudioPlayer import win.taptap.musicmanager.client.playback.AudioPlayer
import win.taptap.musicmanager.client.playback.PlaybackTrack
import win.taptap.musicmanager.client.store.AppStore import win.taptap.musicmanager.client.store.AppStore
@OptIn(ExperimentalCoroutinesApi::class) @OptIn(ExperimentalCoroutinesApi::class)
@@ -45,7 +46,6 @@ class AppStoreTest {
"/api/v1/me" -> respond("""{"name":"alice","admin":false}""", HttpStatusCode.OK, jsonHeaders) "/api/v1/me" -> respond("""{"name":"alice","admin":false}""", HttpStatusCode.OK, jsonHeaders)
"/api/v1/moods" -> respond("""{"moods":[${moodJson(1)}]}""", HttpStatusCode.OK, jsonHeaders) "/api/v1/moods" -> respond("""{"moods":[${moodJson(1)}]}""", HttpStatusCode.OK, jsonHeaders)
"/api/v1/moods/mo-1" -> respond(detailJson(listOf("a")), HttpStatusCode.OK, jsonHeaders) "/api/v1/moods/mo-1" -> respond(detailJson(listOf("a")), HttpStatusCode.OK, jsonHeaders)
"/api/v1/moods/mo-1/preview" -> respond("""{"songs":[]}""", HttpStatusCode.OK, jsonHeaders)
"/api/v1/moods/mo-1/sessions" -> respond( "/api/v1/moods/mo-1/sessions" -> respond(
"""{"id":"s1","moodId":"mo-1","moodName":"Focus","startedAt":"now", """{"id":"s1","moodId":"mo-1","moodName":"Focus","startedAt":"now",
"queue":[${songJson("a")}]}""", "queue":[${songJson("a")}]}""",
@@ -82,7 +82,6 @@ class AppStoreTest {
"/api/v1/me" -> respond("""{"name":"alice","admin":false}""", HttpStatusCode.OK, jsonHeaders) "/api/v1/me" -> respond("""{"name":"alice","admin":false}""", HttpStatusCode.OK, jsonHeaders)
"/api/v1/moods" -> respond("""{"moods":[${moodJson(0)}]}""", HttpStatusCode.OK, jsonHeaders) "/api/v1/moods" -> respond("""{"moods":[${moodJson(0)}]}""", HttpStatusCode.OK, jsonHeaders)
"/api/v1/moods/mo-1" -> respond(detailJson(emptyList()), HttpStatusCode.OK, jsonHeaders) "/api/v1/moods/mo-1" -> respond(detailJson(emptyList()), HttpStatusCode.OK, jsonHeaders)
"/api/v1/moods/mo-1/preview" -> respond("""{"songs":[]}""", HttpStatusCode.OK, jsonHeaders)
else -> respondError(HttpStatusCode.NotFound) else -> respondError(HttpStatusCode.NotFound)
} }
} }
@@ -205,7 +204,6 @@ class AppStoreTest {
HttpStatusCode.OK, HttpStatusCode.OK,
jsonHeaders, jsonHeaders,
) )
"/api/v1/moods/mo-1/preview" -> respond("""{"songs":[]}""", HttpStatusCode.OK, jsonHeaders)
"/api/v1/moods/mo-1/recommendations/v1/add" -> respond( "/api/v1/moods/mo-1/recommendations/v1/add" -> respond(
"""{"detail":${detailJson(listOf("a"))}, """{"detail":${detailJson(listOf("a"))},
"recommendation":${recommendationJson(state = "added", songId = "a")}}""", "recommendation":${recommendationJson(state = "added", songId = "a")}}""",
@@ -245,8 +243,6 @@ class AppStoreTest {
respond(detailJson(emptyList(), source = "deezer"), HttpStatusCode.OK, jsonHeaders) respond(detailJson(emptyList(), source = "deezer"), HttpStatusCode.OK, jsonHeaders)
request.url.encodedPath == "/api/v1/moods/mo-1" -> request.url.encodedPath == "/api/v1/moods/mo-1" ->
respond(detailJson(emptyList()), HttpStatusCode.OK, jsonHeaders) respond(detailJson(emptyList()), HttpStatusCode.OK, jsonHeaders)
request.url.encodedPath == "/api/v1/moods/mo-1/preview" ->
respond("""{"songs":[]}""", HttpStatusCode.OK, jsonHeaders)
request.url.encodedPath == "/api/v1/search" -> { request.url.encodedPath == "/api/v1/search" -> {
val source = request.url.parameters["source"] val source = request.url.parameters["source"]
val body = if (source == "deezer") { val body = if (source == "deezer") {
@@ -271,6 +267,10 @@ class AppStoreTest {
runCurrent() runCurrent()
store.setMoodSource("mo-1", "deezer") store.setMoodSource("mo-1", "deezer")
awaitState("mood source updated") {
store.state.value.moods.first { it.id == "mo-1" }.source == "deezer"
}
// The source change re-runs the search immediately, without debounce.
awaitState { store.state.value.searchResults.any { it.source == "deezer" } } awaitState { store.state.value.searchResults.any { it.source == "deezer" } }
assertEquals("deezer", store.state.value.moods.first { it.id == "mo-1" }.source) assertEquals("deezer", store.state.value.moods.first { it.id == "mo-1" }.source)
@@ -345,7 +345,6 @@ class AppStoreTest {
HttpStatusCode.OK, HttpStatusCode.OK,
jsonHeaders, jsonHeaders,
) )
"/api/v1/moods/mo-1/preview" -> respond("""{"songs":[]}""", HttpStatusCode.OK, jsonHeaders)
"/api/v1/moods/mo-1/sessions" -> respond( "/api/v1/moods/mo-1/sessions" -> respond(
"""{"id":"s1","moodId":"mo-1","moodName":"Focus","startedAt":"now", """{"id":"s1","moodId":"mo-1","moodName":"Focus","startedAt":"now",
"queue":[${songJson("a")},${songJson("b")},${songJson("c")}]}""", "queue":[${songJson("a")},${songJson("b")},${songJson("c")}]}""",
@@ -384,7 +383,6 @@ class AppStoreTest {
"/api/v1/me" -> respond("""{"name":"alice","admin":false}""", HttpStatusCode.OK, jsonHeaders) "/api/v1/me" -> respond("""{"name":"alice","admin":false}""", HttpStatusCode.OK, jsonHeaders)
"/api/v1/moods" -> respond("""{"moods":[${moodJson(3)}]}""", HttpStatusCode.OK, jsonHeaders) "/api/v1/moods" -> respond("""{"moods":[${moodJson(3)}]}""", HttpStatusCode.OK, jsonHeaders)
"/api/v1/moods/mo-1" -> respond(detailJson(listOf("a", "b", "c")), HttpStatusCode.OK, jsonHeaders) "/api/v1/moods/mo-1" -> respond(detailJson(listOf("a", "b", "c")), HttpStatusCode.OK, jsonHeaders)
"/api/v1/moods/mo-1/preview" -> respond("""{"songs":[]}""", HttpStatusCode.OK, jsonHeaders)
"/api/v1/moods/mo-1/sessions" -> respond( "/api/v1/moods/mo-1/sessions" -> respond(
"""{"id":"s1","moodId":"mo-1","moodName":"Focus","startedAt":"now", """{"id":"s1","moodId":"mo-1","moodName":"Focus","startedAt":"now",
"queue":[${songJson("a")},${songJson("b")},${songJson("c")}]}""", "queue":[${songJson("a")},${songJson("b")},${songJson("c")}]}""",
@@ -420,6 +418,96 @@ class AppStoreTest {
store.release() store.release()
} }
@Test
fun `offline mood downloads its songs and remembers the setting`() = runTest {
val storage = MemoryStorage()
val cache = AppCache(storage)
cache.saveSession(SessionState("http://music", "token", User("alice", admin = false)))
val engine = MockEngine { request ->
when (request.url.encodedPath) {
"/api/v1/me" -> respond("""{"name":"alice","admin":false}""", HttpStatusCode.OK, jsonHeaders)
"/api/v1/info" -> respond(
"""{"defaultSource":"deezer","deezerQuality":0,
"loudnessEnabled":true,"loudnessTargetLufs":-16}""",
HttpStatusCode.OK,
jsonHeaders,
)
"/api/v1/moods" -> respond("""{"moods":[${moodJson(1)}]}""", HttpStatusCode.OK, jsonHeaders)
"/api/v1/moods/mo-1" -> respond(detailJson(listOf("a")), HttpStatusCode.OK, jsonHeaders)
"/api/v1/songs/a/stream" -> respond(
byteArrayOf(1, 2, 3, 4),
HttpStatusCode.OK,
headersOf(HttpHeaders.ContentType, "audio/mpeg"),
)
else -> respondError(HttpStatusCode.NotFound)
}
}
val store = store(storage, cache, FakePlayer(), engine)
runCurrent()
store.openMood("mo-1")
awaitState { store.state.value.selectedMood != null }
store.setMoodOffline("mo-1", true)
awaitState("offline download") { "a" in store.state.value.downloads }
assertEquals(setOf("mo-1"), store.state.value.offlineMoods)
assertEquals(setOf("mo-1"), cache.loadSettings().offlineMoods)
store.release()
}
@Test
fun `finish this track pauses at the end of the current song`() = runTest {
val storage = MemoryStorage()
val cache = AppCache(storage)
val player = FakePlayer()
val store = store(storage, cache, player)
runCurrent()
store.playSong(song("a", duration = 180))
awaitState { store.state.value.current?.id == "a" }
player.position = 177.0
advanceTimeBy(500)
runCurrent()
store.setSleepAfterTrack()
assertTrue(store.state.value.sleepAtTrackEnd)
advanceTimeBy(3_500)
runCurrent()
assertFalse(store.state.value.playing)
assertFalse(store.state.value.sleepAtTrackEnd)
store.release()
}
@Test
fun `finish this track does not start the prefetched next song`() = runTest {
val storage = MemoryStorage()
val cache = AppCache(storage)
cache.saveSession(SessionState("http://music", "token", User("alice", admin = false)))
cache.savePlayback(
PlaybackSnapshot(
current = song("a", duration = 180),
queue = listOf(song("b", duration = 180)),
),
)
val player = FakePlayer()
val store = store(storage, cache, player)
runCurrent()
store.togglePlayPause()
awaitState { store.state.value.playing }
store.setSleepAfterTrack()
player.finish()
advanceTimeBy(600)
runCurrent()
assertFalse(store.state.value.playing)
assertEquals("a", store.state.value.current?.id)
assertEquals(listOf("b"), store.state.value.queue.map { it.id })
store.release()
}
@Test @Test
fun `logout clears the session and the mood cache`() = runTest { fun `logout clears the session and the mood cache`() = runTest {
val storage = MemoryStorage() val storage = MemoryStorage()
@@ -532,22 +620,6 @@ class AppStoreTest {
) )
private class FakePlayer : AudioPlayer { private class FakePlayer : AudioPlayer {
private var onNext: (() -> Unit)? = null
private var onPrevious: (() -> Unit)? = null
fun pressNext() {
onNext?.invoke()
}
fun pressPrevious() {
onPrevious?.invoke()
}
override fun setSkipCallbacks(onNext: (() -> Unit)?, onPrevious: (() -> Unit)?) {
this.onNext = onNext
this.onPrevious = onPrevious
}
val played = mutableListOf<String>() val played = mutableListOf<String>()
val seeks = mutableListOf<Double>() val seeks = mutableListOf<Double>()
var paused = false var paused = false
@@ -555,25 +627,79 @@ class AppStoreTest {
private var playing = false private var playing = false
var position = 0.0 var position = 0.0
private var finished = false private var finished = false
private var tracks: List<PlaybackTrack> = emptyList()
private var index = 0
fun finish() { fun pressNext() {
finished = true skipToNext()
} }
override fun play( fun pressPrevious() {
source: String, skipToPrevious(2.0)
song: Song, }
local: Boolean,
artworkUri: String?, override fun setQueue(tracks: List<PlaybackTrack>, startIndex: Int, startAtSeconds: Double) {
artworkBytes: ByteArray?, this.tracks = tracks
) { index = startIndex.coerceIn(tracks.indices)
played += song.id startCurrent(startAtSeconds)
}
override fun appendToQueue(tracks: List<PlaybackTrack>) {
this.tracks = this.tracks + tracks
}
override fun moveInQueue(fromIndex: Int, toIndex: Int) {
if (fromIndex !in tracks.indices || toIndex !in tracks.indices) return
val moved = tracks.toMutableList()
val item = moved.removeAt(fromIndex)
moved.add(toIndex, item)
tracks = moved
if (index == fromIndex) index = toIndex
}
override fun removeAt(index: Int) {
if (index !in tracks.indices) return
tracks = tracks.filterIndexed { i, _ -> i != index }
if (index < this.index) this.index = (this.index - 1).coerceAtLeast(0)
}
override fun playIndex(index: Int, startAtSeconds: Double) {
if (index !in tracks.indices) return
this.index = index
startCurrent(startAtSeconds)
}
private fun startCurrent(startAtSeconds: Double) {
val track = tracks.getOrNull(index) ?: return
played += track.song.id
playing = true playing = true
paused = false paused = false
position = 0.0 position = startAtSeconds
seeks += startAtSeconds
finished = false finished = false
} }
override fun skipToNext() {
if (index + 1 < tracks.size) {
playIndex(index + 1, 0.0)
} else {
finished = true
playing = false
}
}
override fun skipToPrevious(restartAfterSeconds: Double) {
if (position > restartAfterSeconds || index == 0) {
seekTo(0.0)
} else {
playIndex(index - 1, 0.0)
}
}
override fun currentIndex(): Int = index
override fun queueSize(): Int = tracks.size
override fun pause() { override fun pause() {
playing = false playing = false
paused = true paused = true
@@ -591,12 +717,21 @@ class AppStoreTest {
override fun isPlaying(): Boolean = playing override fun isPlaying(): Boolean = playing
override fun isFinished(): Boolean = finished override fun isFinished(): Boolean = finished
override fun positionSeconds(): Double = position override fun positionSeconds(): Double = position
override fun durationSeconds(): Double = 0.0 override fun durationSeconds(): Double =
tracks.getOrNull(index)?.song?.duration?.toDouble() ?: 0.0
override val canSeek: Boolean = true override val canSeek: Boolean = true
override fun seekTo(seconds: Double) { override fun seekTo(seconds: Double) {
position = seconds position = seconds
seeks += seconds seeks += seconds
} }
fun finish() {
finished = true
playing = false
}
override fun release() { override fun release() {
playing = false playing = false
} }
@@ -1,11 +1,13 @@
package win.taptap.musicmanager.client package win.taptap.musicmanager.client
import io.ktor.utils.io.readAvailable
import win.taptap.musicmanager.client.data.AppStorage import win.taptap.musicmanager.client.data.AppStorage
/** In-memory [AppStorage] for store and cache tests. */ /** In-memory [AppStorage] for store and cache tests. */
internal class MemoryStorage : AppStorage { internal class MemoryStorage : AppStorage {
private val files = mutableMapOf<String, String>() private val files = mutableMapOf<String, String>()
private val artwork = mutableMapOf<String, ByteArray>() private val artwork = mutableMapOf<String, ByteArray>()
private val downloads = mutableMapOf<String, ByteArray>()
override fun read(name: String): String? = files[name] override fun read(name: String): String? = files[name]
@@ -17,16 +19,40 @@ internal class MemoryStorage : AppStorage {
files.remove(name) files.remove(name)
} }
override fun saveDownload(songId: String, bytes: ByteArray): String? = null override fun saveDownload(songId: String, bytes: ByteArray): String? {
override fun downloadPath(songId: String): String? = null downloads[songId] = bytes
return "memory://$songId.mp3"
}
override suspend fun saveDownloadStream(
songId: String,
source: io.ktor.utils.io.ByteReadChannel,
): String? {
val bytes = ArrayList<Byte>()
val buffer = ByteArray(8 * 1024)
while (true) {
val read = source.readAvailable(buffer)
if (read < 0) break
for (i in 0 until read) bytes += buffer[i]
}
downloads[songId] = bytes.toByteArray()
return "memory://$songId.mp3"
}
override fun downloadPath(songId: String): String? =
downloads[songId]?.let { "memory://$songId.mp3" }
override fun saveArtwork(songId: String, bytes: ByteArray): String? { override fun saveArtwork(songId: String, bytes: ByteArray): String? {
artwork[songId] = bytes artwork[songId] = bytes
return "memory://$songId.jpg" return "memory://$songId.jpg"
} }
override fun artworkBytes(songId: String): ByteArray? = artwork[songId] override fun artworkBytes(songId: String): ByteArray? = artwork[songId]
override fun listDownloads(): Map<String, Long> = emptyMap() override fun listDownloads(): Map<String, Long> =
downloads.mapValues { it.value.size.toLong() }
override fun deleteDownload(songId: String) { override fun deleteDownload(songId: String) {
artwork.remove(songId) artwork.remove(songId)
downloads.remove(songId)
} }
override fun storageUsedBytes(): Long = 0
override fun storageUsedBytes(): Long = downloads.values.sumOf { it.size.toLong() }
} }
@@ -8,23 +8,24 @@ import java.net.URI
import javax.sound.sampled.AudioFormat import javax.sound.sampled.AudioFormat
import javax.sound.sampled.AudioInputStream import javax.sound.sampled.AudioInputStream
import javax.sound.sampled.AudioSystem import javax.sound.sampled.AudioSystem
import javax.sound.sampled.FloatControl
import javax.sound.sampled.SourceDataLine import javax.sound.sampled.SourceDataLine
import kotlin.concurrent.thread import kotlin.concurrent.thread
import win.taptap.musicmanager.client.api.Song import kotlin.math.pow
import win.taptap.musicmanager.client.playback.AudioPlayer import win.taptap.musicmanager.client.playback.AudioPlayer
import win.taptap.musicmanager.client.playback.PlaybackTrack
/** /**
* Desktop playback through the MP3SPI decoder and a PCM line. Pause/resume is a * Desktop playback through the MP3SPI decoder and a PCM line. Pause/resume is a
* decoder loop gate, so no audio device is reopened. * decoder loop gate, so no audio device is reopened.
* *
* The queue is kept here so the store can use the same timeline operations as
* Android. Desktop has no media service, so the store advances to the next item
* when the decoder reaches the end.
*
* Seeking restarts the decoder at the requested position. Remote streams ask * Seeking restarts the decoder at the requested position. Remote streams ask
* the server to transcode from that offset (`timeOffset`); local files skip the * the server to transcode from that offset (`timeOffset`); local files skip the
* decoded PCM frames. Both keep the reported position aligned with the song. * decoded PCM frames. Both keep the reported position aligned with the song.
*
* Java Sound cannot open a line for the compressed MP3 format itself; the
* decoded stream has to be converted to PCM_SIGNED first. Opening the encoded
* format fails with "No line matching interface SourceDataLine supporting
* format MPEG1L3 ...".
*/ */
class DesktopAudioPlayer : AudioPlayer { class DesktopAudioPlayer : AudioPlayer {
@@ -34,10 +35,10 @@ class DesktopAudioPlayer : AudioPlayer {
private var worker: Thread? = null private var worker: Thread? = null
private val lock = Object() private val lock = Object()
private var currentSource: String? = null private var tracks: List<PlaybackTrack> = emptyList()
private var currentSong: Song? = null private var index = 0
private var currentLocal = false private var currentTrack: PlaybackTrack? = null
private var currentArtwork: String? = null private var gain = 1f
@Volatile private var paused = false @Volatile private var paused = false
@Volatile private var stopped = false @Volatile private var stopped = false
@@ -48,29 +49,78 @@ class DesktopAudioPlayer : AudioPlayer {
private var frameRate = 44_100f private var frameRate = 44_100f
private var duration = 0.0 private var duration = 0.0
override fun play( override fun setQueue(tracks: List<PlaybackTrack>, startIndex: Int, startAtSeconds: Double) {
source: String, if (tracks.isEmpty()) return
song: Song, this.tracks = tracks
local: Boolean, index = startIndex.coerceIn(tracks.indices)
artworkUri: String?, playIndex(index, startAtSeconds)
artworkBytes: ByteArray?,
) {
currentSource = source
currentSong = song
currentLocal = local
currentArtwork = artworkUri
start(source, song, local, startAtSeconds = 0.0)
} }
private fun start(source: String, song: Song, local: Boolean, startAtSeconds: Double) { override fun appendToQueue(tracks: List<PlaybackTrack>) {
this.tracks = this.tracks + tracks
}
override fun moveInQueue(fromIndex: Int, toIndex: Int) {
if (fromIndex !in tracks.indices || toIndex !in tracks.indices || fromIndex == toIndex) return
val moved = tracks.toMutableList()
val item = moved.removeAt(fromIndex)
moved.add(toIndex, item)
tracks = moved
if (index == fromIndex) {
index = toIndex
} else if (fromIndex < index && toIndex >= index) {
index -= 1
} else if (fromIndex > index && toIndex <= index) {
index += 1
}
}
override fun removeAt(index: Int) {
if (index !in tracks.indices) return
tracks = tracks.filterIndexed { i, _ -> i != index }
if (index < this.index) this.index = (this.index - 1).coerceAtLeast(0)
}
override fun playIndex(index: Int, startAtSeconds: Double) {
val track = tracks.getOrNull(index) ?: return
this.index = index
currentTrack = track
gain = track.gainDb?.let { 10.0.pow(it / 20.0).toFloat() }?.coerceIn(0f, 4f) ?: 1f
start(track, startAtSeconds)
}
override fun skipToNext() {
if (index + 1 < tracks.size) {
playIndex(index + 1)
} else {
finished = true
stop()
}
}
override fun skipToPrevious(restartAfterSeconds: Double) {
if (positionSeconds() > restartAfterSeconds || index == 0) {
seekTo(0.0)
} else {
playIndex(index - 1)
}
}
override fun currentIndex(): Int = index
override fun queueSize(): Int = tracks.size
private fun start(track: PlaybackTrack, startAtSeconds: Double) {
stop() stop()
finished = false finished = false
paused = false paused = false
stopped = false stopped = false
framesRead = 0 framesRead = 0
baseSeconds = startAtSeconds.coerceAtLeast(0.0) baseSeconds = startAtSeconds.coerceAtLeast(0.0)
duration = song.duration.toDouble() duration = track.song.duration.toDouble()
val source = track.source
val local = track.local
val requestSource = if (!local && startAtSeconds > 0) { val requestSource = if (!local && startAtSeconds > 0) {
withTimeOffset(source, startAtSeconds) withTimeOffset(source, startAtSeconds)
} else { } else {
@@ -102,6 +152,7 @@ class DesktopAudioPlayer : AudioPlayer {
val info = javax.sound.sampled.DataLine.Info(SourceDataLine::class.java, audio.format) val info = javax.sound.sampled.DataLine.Info(SourceDataLine::class.java, audio.format)
val dataLine = AudioSystem.getLine(info) as SourceDataLine val dataLine = AudioSystem.getLine(info) as SourceDataLine
dataLine.open(audio.format) dataLine.open(audio.format)
applyGain(dataLine)
dataLine.start() dataLine.start()
line = dataLine line = dataLine
@@ -133,6 +184,14 @@ class DesktopAudioPlayer : AudioPlayer {
} }
} }
private fun applyGain(dataLine: SourceDataLine) {
val control = runCatching {
dataLine.getControl(FloatControl.Type.MASTER_GAIN) as FloatControl
}.getOrNull() ?: return
val db = 20.0 * kotlin.math.log10(gain.coerceAtLeast(0.0001f).toDouble())
control.value = db.coerceIn(control.minimum.toDouble(), control.maximum.toDouble()).toFloat()
}
private fun skipPcm(audio: AudioInputStream, seconds: Double) { private fun skipPcm(audio: AudioInputStream, seconds: Double) {
var remaining = (seconds * frameRate * frameSize).toLong().coerceAtLeast(0L) var remaining = (seconds * frameRate * frameSize).toLong().coerceAtLeast(0L)
val buffer = ByteArray(16 * 1024) val buffer = ByteArray(16 * 1024)
@@ -192,15 +251,15 @@ class DesktopAudioPlayer : AudioPlayer {
override val canSeek: Boolean = true override val canSeek: Boolean = true
override fun seekTo(seconds: Double) { override fun seekTo(seconds: Double) {
val source = currentSource ?: return val track = currentTrack ?: return
val song = currentSong ?: return
val wasPaused = paused val wasPaused = paused
start(source, song, currentLocal, seconds.coerceAtLeast(0.0)) start(track, seconds.coerceAtLeast(0.0))
if (wasPaused) pause() if (wasPaused) pause()
} }
override fun release() { override fun release() {
stop() stop()
tracks = emptyList()
} }
/** Adds the server's `timeOffset` parameter, replacing an earlier one. */ /** Adds the server's `timeOffset` parameter, replacing an earlier one. */
@@ -124,3 +124,5 @@ class DesktopStorage : AppStorage {
actual fun decodeImage(bytes: ByteArray): ImageBitmap? = actual fun decodeImage(bytes: ByteArray): ImageBitmap? =
runCatching { org.jetbrains.skia.Image.makeFromEncoded(bytes).toComposeImageBitmap() }.getOrNull() runCatching { org.jetbrains.skia.Image.makeFromEncoded(bytes).toComposeImageBitmap() }.getOrNull()
actual fun isUnmeteredNetwork(): Boolean = true
@@ -47,3 +47,5 @@ actual fun PlatformBackHandler(enabled: Boolean, onBack: () -> Unit) {
actual fun decodeImage(bytes: ByteArray): ImageBitmap? = actual fun decodeImage(bytes: ByteArray): ImageBitmap? =
runCatching { org.jetbrains.skia.Image.makeFromEncoded(bytes).toComposeImageBitmap() }.getOrNull() runCatching { org.jetbrains.skia.Image.makeFromEncoded(bytes).toComposeImageBitmap() }.getOrNull()
actual fun isUnmeteredNetwork(): Boolean = true
@@ -1,10 +1,15 @@
package win.taptap.musicmanager.client package win.taptap.musicmanager.client
import kotlinx.browser.document import kotlin.math.pow
import org.w3c.dom.HTMLAudioElement import org.w3c.dom.HTMLAudioElement
import win.taptap.musicmanager.client.api.Song import kotlinx.browser.document
import win.taptap.musicmanager.client.playback.AudioPlayer import win.taptap.musicmanager.client.playback.AudioPlayer
import win.taptap.musicmanager.client.playback.PlaybackTrack
/**
* Browser playback. The queue lives here like on the other targets; the store
* advances at the end because HTMLAudioElement has one source at a time.
*/
class WebAudioPlayer : AudioPlayer { class WebAudioPlayer : AudioPlayer {
private val audio: HTMLAudioElement = private val audio: HTMLAudioElement =
@@ -12,17 +17,72 @@ class WebAudioPlayer : AudioPlayer {
preload = "auto" preload = "auto"
} }
override fun play( private var tracks: List<PlaybackTrack> = emptyList()
source: String, private var index = 0
song: Song, private var gain = 1.0
local: Boolean,
artworkUri: String?, override fun setQueue(tracks: List<PlaybackTrack>, startIndex: Int, startAtSeconds: Double) {
artworkBytes: ByteArray?, if (tracks.isEmpty()) return
) { this.tracks = tracks
audio.src = source index = startIndex.coerceIn(tracks.indices)
playIndex(index, startAtSeconds)
}
override fun appendToQueue(tracks: List<PlaybackTrack>) {
this.tracks = this.tracks + tracks
}
override fun moveInQueue(fromIndex: Int, toIndex: Int) {
if (fromIndex !in tracks.indices || toIndex !in tracks.indices || fromIndex == toIndex) return
val moved = tracks.toMutableList()
val item = moved.removeAt(fromIndex)
moved.add(toIndex, item)
tracks = moved
if (index == fromIndex) {
index = toIndex
} else if (fromIndex < index && toIndex >= index) {
index -= 1
} else if (fromIndex > index && toIndex <= index) {
index += 1
}
}
override fun removeAt(index: Int) {
if (index !in tracks.indices) return
tracks = tracks.filterIndexed { i, _ -> i != index }
if (index < this.index) this.index = (this.index - 1).coerceAtLeast(0)
}
override fun playIndex(index: Int, startAtSeconds: Double) {
val track = tracks.getOrNull(index) ?: return
this.index = index
gain = track.gainDb?.let { 10.0.pow(it / 20.0) }?.coerceIn(0.0, 1.0) ?: 1.0
audio.volume = gain
audio.src = track.source
if (startAtSeconds > 0) audio.currentTime = startAtSeconds
audio.play() audio.play()
} }
override fun skipToNext() {
if (index + 1 < tracks.size) {
playIndex(index + 1)
} else {
audio.pause()
}
}
override fun skipToPrevious(restartAfterSeconds: Double) {
if (positionSeconds() > restartAfterSeconds || index == 0) {
seekTo(0.0)
} else {
playIndex(index - 1)
}
}
override fun currentIndex(): Int = index
override fun queueSize(): Int = tracks.size
override fun pause() { override fun pause() {
audio.pause() audio.pause()
} }
@@ -54,5 +114,6 @@ class WebAudioPlayer : AudioPlayer {
override fun release() { override fun release() {
stop() stop()
tracks = emptyList()
} }
} }