feat: service-owned queue, full player, audio consistency and mood settings
- 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
This commit is contained in:
1 parent
8d7f6a0ccb
commit
1e3dac4e47
26 files changed
+2060
-661
No files matched your search
@@ -37,9 +37,8 @@ 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.
|
||||||
@@ -48,15 +47,23 @@ a server-driven radio session and songs are added from Deezer or YouTube Music.
|
|||||||
- **Headset/Bluetooth next and previous** and the media notification's skip /
|
- **Headset/Bluetooth next and previous** and the media notification's skip /
|
||||||
back buttons use the same queue rules as the in-app controls; they no longer
|
back buttons use the same queue rules as the in-app controls; they no longer
|
||||||
seek inside the single ExoPlayer item.
|
seek inside the single ExoPlayer item.
|
||||||
- The bottom player keeps the cover and title/artist readable on narrow phones;
|
- The bottom player keeps the cover and title/artist readable on narrow phones.
|
||||||
add-to-mood actions moved into the overflow menu.
|
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
|
||||||
@@ -72,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.
|
||||||
@@ -80,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.
|
||||||
|
|
||||||
@@ -200,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.3 && git push --tags` builds, signs and uploads the bundle.
|
Then `git tag v0.4.0 && 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.
|
||||||
|
|
||||||
@@ -264,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.
|
||||||
|
|||||||
@@ -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.3"
|
?: "0.4.0"
|
||||||
|
|
||||||
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" />
|
||||||
|
|||||||
+105
@@ -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()
|
||||||
|
}
|
||||||
+86
-40
@@ -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,42 +55,55 @@ 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)
|
override fun appendToQueue(tracks: List<PlaybackTrack>) {
|
||||||
controller.prepare()
|
if (tracks.isEmpty()) return
|
||||||
controller.play()
|
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,39 @@ 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 {
|
||||||
|
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
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+107
-71
@@ -5,11 +5,10 @@ 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.ForwardingPlayer
|
||||||
|
import androidx.media3.common.MediaItem
|
||||||
import androidx.media3.common.Player
|
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
|
||||||
@@ -24,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() {
|
||||||
|
|
||||||
@@ -37,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 exoPlayer = 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)
|
||||||
@@ -53,44 +94,47 @@ class PlaybackService : MediaSessionService() {
|
|||||||
.apply {
|
.apply {
|
||||||
setWakeMode(C.WAKE_MODE_NETWORK)
|
setWakeMode(C.WAKE_MODE_NETWORK)
|
||||||
}
|
}
|
||||||
|
player = exoPlayer
|
||||||
|
|
||||||
// ExoPlayer holds one item at a time; the queue lives in the app. Advertise
|
// Media3's notification/next/previous map onto the real timeline. The
|
||||||
// next/previous so the notification and Android Auto show the buttons and
|
// only custom rule is Android's usual previous behaviour: after two
|
||||||
// route them to the queue instead of seeking inside the single item.
|
// seconds of playback it restarts the current item.
|
||||||
val player = object : ForwardingPlayer(exoPlayer) {
|
val sessionPlayer = object : ForwardingPlayer(exoPlayer) {
|
||||||
override fun getAvailableCommands(): Player.Commands =
|
|
||||||
super.getAvailableCommands().buildUpon()
|
|
||||||
.addAll(
|
|
||||||
Player.COMMAND_SEEK_TO_NEXT,
|
|
||||||
Player.COMMAND_SEEK_TO_NEXT_MEDIA_ITEM,
|
|
||||||
Player.COMMAND_SEEK_TO_PREVIOUS,
|
|
||||||
Player.COMMAND_SEEK_TO_PREVIOUS_MEDIA_ITEM,
|
|
||||||
)
|
|
||||||
.build()
|
|
||||||
|
|
||||||
override fun isCommandAvailable(command: Int): Boolean =
|
|
||||||
command == Player.COMMAND_SEEK_TO_NEXT ||
|
|
||||||
command == Player.COMMAND_SEEK_TO_NEXT_MEDIA_ITEM ||
|
|
||||||
command == Player.COMMAND_SEEK_TO_PREVIOUS ||
|
|
||||||
command == Player.COMMAND_SEEK_TO_PREVIOUS_MEDIA_ITEM ||
|
|
||||||
super.isCommandAvailable(command)
|
|
||||||
|
|
||||||
override fun seekToNext() {
|
|
||||||
if (!PlaybackCommands.next()) super.seekToNext()
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun seekToNextMediaItem() {
|
|
||||||
if (!PlaybackCommands.next()) super.seekToNextMediaItem()
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun seekToPrevious() {
|
override fun seekToPrevious() {
|
||||||
if (!PlaybackCommands.previous()) super.seekToPrevious()
|
if (exoPlayer.currentPosition > PREVIOUS_RESTART_MS) {
|
||||||
|
exoPlayer.seekTo(0)
|
||||||
|
} else if (exoPlayer.hasPreviousMediaItem()) {
|
||||||
|
exoPlayer.seekToPreviousMediaItem()
|
||||||
|
} else {
|
||||||
|
exoPlayer.seekTo(0)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun seekToPreviousMediaItem() {
|
override fun seekToPreviousMediaItem() {
|
||||||
if (!PlaybackCommands.previous()) super.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,
|
||||||
@@ -99,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(
|
||||||
@@ -109,64 +153,49 @@ 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))
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.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
|
||||||
|
|
||||||
@@ -179,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,6 +184,8 @@ class ApiClient(private val http: HttpClient) {
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
|
suspend fun info(): ServerInfo = get("/info")
|
||||||
|
|
||||||
suspend fun search(
|
suspend fun search(
|
||||||
query: String,
|
query: String,
|
||||||
limit: Int = 10,
|
limit: Int = 10,
|
||||||
|
|||||||
@@ -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"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+34
-19
@@ -2,20 +2,39 @@ 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,
|
||||||
|
/** 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 +44,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
|
|
||||||
}
|
}
|
||||||
|
|
||||||
+489
-207
@@ -19,22 +19,26 @@ import win.taptap.musicmanager.client.api.Mood
|
|||||||
import win.taptap.musicmanager.client.api.MoodDetail
|
import win.taptap.musicmanager.client.api.MoodDetail
|
||||||
import win.taptap.musicmanager.client.api.PlaybackEvent
|
import win.taptap.musicmanager.client.api.PlaybackEvent
|
||||||
import win.taptap.musicmanager.client.api.SearchResult
|
import win.taptap.musicmanager.client.api.SearchResult
|
||||||
|
import win.taptap.musicmanager.client.api.ServerInfo
|
||||||
import win.taptap.musicmanager.client.api.Session
|
import win.taptap.musicmanager.client.api.Session
|
||||||
import win.taptap.musicmanager.client.api.Song
|
import win.taptap.musicmanager.client.api.Song
|
||||||
import win.taptap.musicmanager.client.api.UpdateMoodRequest
|
import win.taptap.musicmanager.client.api.UpdateMoodRequest
|
||||||
import win.taptap.musicmanager.client.api.configuredHttpClient
|
import win.taptap.musicmanager.client.api.configuredHttpClient
|
||||||
import win.taptap.musicmanager.client.createAudioPlayer
|
import win.taptap.musicmanager.client.createAudioPlayer
|
||||||
|
import win.taptap.musicmanager.client.isUnmeteredNetwork
|
||||||
import win.taptap.musicmanager.client.data.AppCache
|
import win.taptap.musicmanager.client.data.AppCache
|
||||||
|
import win.taptap.musicmanager.client.data.ClientSettings
|
||||||
import win.taptap.musicmanager.client.data.CachedState
|
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.data.AppStorage
|
import win.taptap.musicmanager.client.data.AppStorage
|
||||||
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.platformEngine
|
import win.taptap.musicmanager.client.platformEngine
|
||||||
import win.taptap.musicmanager.client.platformName
|
import win.taptap.musicmanager.client.platformName
|
||||||
import win.taptap.musicmanager.client.platformStorage
|
import win.taptap.musicmanager.client.platformStorage
|
||||||
|
|
||||||
enum class Screen { Moods, MoodDetail, Search, Downloads, Settings }
|
enum class Screen { Moods, MoodDetail, MoodSettings, Search, Downloads, Settings, NowPlaying }
|
||||||
|
|
||||||
data class AppState(
|
data class AppState(
|
||||||
val booting: Boolean = true,
|
val booting: Boolean = true,
|
||||||
@@ -53,7 +57,19 @@ data class AppState(
|
|||||||
val positionSeconds: Double = 0.0,
|
val positionSeconds: Double = 0.0,
|
||||||
val durationSeconds: Double = 0.0,
|
val durationSeconds: Double = 0.0,
|
||||||
val sleepTimerRemainingSeconds: Long? = null,
|
val sleepTimerRemainingSeconds: Long? = null,
|
||||||
|
/** True when the timer will stop after the current track instead of a countdown. */
|
||||||
|
val sleepAtTrackEnd: Boolean = false,
|
||||||
val downloads: Set<String> = emptySet(),
|
val downloads: Set<String> = emptySet(),
|
||||||
|
/** Moods kept downloaded on this device and auto-synced on Wi-Fi. */
|
||||||
|
val offlineMoods: Set<String> = emptySet(),
|
||||||
|
val normalizationEnabled: Boolean = true,
|
||||||
|
/** 0 = gapless, otherwise the fade length in seconds. */
|
||||||
|
val crossfadeSeconds: Int = 0,
|
||||||
|
val serverInfo: ServerInfo? = null,
|
||||||
|
/** Where the full-screen player returns when it is closed. */
|
||||||
|
val nowPlayingReturn: Screen = Screen.Moods,
|
||||||
|
/** Where the search screen returns when it is closed. */
|
||||||
|
val searchReturn: Screen = Screen.Moods,
|
||||||
val downloading: Set<String> = emptySet(),
|
val downloading: Set<String> = emptySet(),
|
||||||
/** Metadata for songs seen in moods, queues and the cache, used by Downloads. */
|
/** Metadata for songs seen in moods, queues and the cache, used by Downloads. */
|
||||||
val knownSongs: Map<String, Song> = emptyMap(),
|
val knownSongs: Map<String, Song> = emptyMap(),
|
||||||
@@ -91,20 +107,21 @@ class AppStore(
|
|||||||
private var searchJob: Job? = null
|
private var searchJob: Job? = null
|
||||||
private var reconnectJob: Job? = null
|
private var reconnectJob: Job? = null
|
||||||
private var playbackStarted = false
|
private var playbackStarted = false
|
||||||
private var advancing = false
|
|
||||||
private var fetching = false
|
private var fetching = false
|
||||||
private var finishing = false
|
|
||||||
private var pollTicks = 0
|
private var pollTicks = 0
|
||||||
private var trackStartOffset = 0.0
|
private var suppressCompletion = false
|
||||||
|
private var playbackGeneration = 0
|
||||||
|
private var timelineSongs: List<Song> = emptyList()
|
||||||
|
private var trackIndex = 0
|
||||||
private var dataGeneration = 0
|
private var dataGeneration = 0
|
||||||
private var moodRequestGeneration = 0
|
private var moodRequestGeneration = 0
|
||||||
private var searchTargetGeneration = 0
|
private var searchTargetGeneration = 0
|
||||||
private var loggingOut = false
|
private var loggingOut = false
|
||||||
|
private var settings = ClientSettings()
|
||||||
|
/** Tracks whose last offline download failed; retried on the next mood open. */
|
||||||
|
private val offlineFailed = mutableSetOf<String>()
|
||||||
|
|
||||||
init {
|
init {
|
||||||
// Headset/Bluetooth next and previous must use the app queue rules,
|
|
||||||
// not ExoPlayer's single-item seek-to-start.
|
|
||||||
player.setSkipCallbacks(onNext = ::skip, onPrevious = ::previous)
|
|
||||||
bootstrap()
|
bootstrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -113,8 +130,16 @@ class AppStore(
|
|||||||
val session = cache.loadSession()
|
val session = cache.loadSession()
|
||||||
val cached = cache.load()
|
val cached = cache.load()
|
||||||
val playback = cache.loadPlayback()
|
val playback = cache.loadPlayback()
|
||||||
|
val loadedSettings = cache.loadSettings()
|
||||||
|
settings = loadedSettings
|
||||||
|
player.setCrossfadeSeconds(loadedSettings.crossfadeSeconds)
|
||||||
val restoredSong = playback?.current
|
val restoredSong = playback?.current
|
||||||
|
|
||||||
|
val restoredTimeline = playback?.let { snapshot ->
|
||||||
|
snapshot.history + listOfNotNull(snapshot.current) + snapshot.queue
|
||||||
|
}.orEmpty()
|
||||||
|
timelineSongs = restoredTimeline
|
||||||
|
trackIndex = playback?.history?.size ?: 0
|
||||||
_state.update {
|
_state.update {
|
||||||
it.copy(
|
it.copy(
|
||||||
booting = false,
|
booting = false,
|
||||||
@@ -128,6 +153,9 @@ class AppStore(
|
|||||||
history = playback?.history.orEmpty(),
|
history = playback?.history.orEmpty(),
|
||||||
positionSeconds = playback?.positionSeconds ?: 0.0,
|
positionSeconds = playback?.positionSeconds ?: 0.0,
|
||||||
durationSeconds = restoredSong?.duration?.toDouble() ?: 0.0,
|
durationSeconds = restoredSong?.duration?.toDouble() ?: 0.0,
|
||||||
|
offlineMoods = loadedSettings.offlineMoods,
|
||||||
|
normalizationEnabled = loadedSettings.normalizationEnabled,
|
||||||
|
crossfadeSeconds = loadedSettings.crossfadeSeconds,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -223,6 +251,7 @@ class AppStore(
|
|||||||
cache.loadSession()?.let { session -> cache.saveSession(session.copy(user = me)) }
|
cache.loadSession()?.let { session -> cache.saveSession(session.copy(user = me)) }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
val modules = runCatching { api.info() }.getOrNull()
|
||||||
val moods = api.moods()
|
val moods = api.moods()
|
||||||
val loaded = cache.load()
|
val loaded = cache.load()
|
||||||
val cacheMatches = loaded.serverUrl == _state.value.serverUrl &&
|
val cacheMatches = loaded.serverUrl == _state.value.serverUrl &&
|
||||||
@@ -248,8 +277,11 @@ class AppStore(
|
|||||||
user = currentUser,
|
user = currentUser,
|
||||||
moods = moods,
|
moods = moods,
|
||||||
knownSongs = it.knownSongs + details.songMap(null),
|
knownSongs = it.knownSongs + details.songMap(null),
|
||||||
|
serverInfo = modules ?: it.serverInfo,
|
||||||
|
offlineMoods = settings.offlineMoods,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
syncOfflineMoods()
|
||||||
} catch (t: Throwable) {
|
} catch (t: Throwable) {
|
||||||
if (t is ApiException && t.status == 401) {
|
if (t is ApiException && t.status == 401) {
|
||||||
logout()
|
logout()
|
||||||
@@ -294,6 +326,8 @@ class AppStore(
|
|||||||
knownSongs = it.knownSongs + detail.songMap(),
|
knownSongs = it.knownSongs + detail.songMap(),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
offlineFailed.clear()
|
||||||
|
syncOfflineMoods()
|
||||||
} catch (t: Throwable) {
|
} catch (t: Throwable) {
|
||||||
if (request != moodRequestGeneration) return@launch
|
if (request != moodRequestGeneration) return@launch
|
||||||
val cached = cache.load().moodDetails.firstOrNull { it.mood.id == id }
|
val cached = cache.load().moodDetails.firstOrNull { it.mood.id == id }
|
||||||
@@ -329,6 +363,7 @@ class AppStore(
|
|||||||
?: it.moods.firstOrNull()?.id
|
?: it.moods.firstOrNull()?.id
|
||||||
it.copy(
|
it.copy(
|
||||||
screen = Screen.Search,
|
screen = Screen.Search,
|
||||||
|
searchReturn = if (it.screen == Screen.Search) it.searchReturn else it.screen,
|
||||||
searchTargetMoodId = target,
|
searchTargetMoodId = target,
|
||||||
searchResults = emptyList(),
|
searchResults = emptyList(),
|
||||||
searchQuery = "",
|
searchQuery = "",
|
||||||
@@ -345,6 +380,90 @@ class AppStore(
|
|||||||
_state.update { it.copy(screen = Screen.Settings) }
|
_state.update { it.copy(screen = Screen.Settings) }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun openMoodSettings() {
|
||||||
|
if (_state.value.selectedMood == null) return
|
||||||
|
_state.update { it.copy(screen = Screen.MoodSettings) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun openNowPlaying() {
|
||||||
|
if (_state.value.current == null) return
|
||||||
|
_state.update {
|
||||||
|
it.copy(
|
||||||
|
nowPlayingReturn = if (it.screen == Screen.NowPlaying) it.nowPlayingReturn else it.screen,
|
||||||
|
screen = Screen.NowPlaying,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun closeNowPlaying() {
|
||||||
|
_state.update {
|
||||||
|
it.copy(screen = if (it.screen == Screen.NowPlaying) it.nowPlayingReturn else it.screen)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One back action for every screen, including the full-screen player. */
|
||||||
|
fun back() {
|
||||||
|
val state = _state.value
|
||||||
|
when (state.screen) {
|
||||||
|
Screen.Moods -> Unit
|
||||||
|
Screen.MoodDetail -> openMoods()
|
||||||
|
Screen.MoodSettings -> _state.update { it.copy(screen = Screen.MoodDetail) }
|
||||||
|
Screen.NowPlaying -> closeNowPlaying()
|
||||||
|
Screen.Search -> {
|
||||||
|
val target = state.searchTargetMoodId
|
||||||
|
when {
|
||||||
|
state.searchReturn == Screen.Moods || target == null -> openMoods()
|
||||||
|
target == state.selectedMood?.mood?.id ->
|
||||||
|
_state.update { it.copy(screen = Screen.MoodDetail) }
|
||||||
|
else -> openMood(target)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Screen.Downloads, Screen.Settings -> openMoods()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Toggles the per-mood offline copy and starts syncing it immediately. */
|
||||||
|
fun setMoodOffline(moodId: String, offline: Boolean) {
|
||||||
|
settings = settings.copy(
|
||||||
|
offlineMoods = if (offline) {
|
||||||
|
settings.offlineMoods + moodId
|
||||||
|
} else {
|
||||||
|
settings.offlineMoods - moodId
|
||||||
|
},
|
||||||
|
)
|
||||||
|
cache.saveSettings(settings)
|
||||||
|
_state.update {
|
||||||
|
it.copy(
|
||||||
|
offlineMoods = settings.offlineMoods,
|
||||||
|
message = if (offline) {
|
||||||
|
"Keeping this mood offline"
|
||||||
|
} else {
|
||||||
|
"Offline copy disabled"
|
||||||
|
},
|
||||||
|
messageIsError = false,
|
||||||
|
messageId = it.messageId + 1,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (offline) {
|
||||||
|
offlineFailed.clear()
|
||||||
|
syncOfflineMoods()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setNormalizationEnabled(enabled: Boolean) {
|
||||||
|
settings = settings.copy(normalizationEnabled = enabled)
|
||||||
|
cache.saveSettings(settings)
|
||||||
|
_state.update { it.copy(normalizationEnabled = enabled) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setCrossfadeSeconds(seconds: Int) {
|
||||||
|
val value = seconds.coerceIn(0, 8)
|
||||||
|
settings = settings.copy(crossfadeSeconds = value)
|
||||||
|
cache.saveSettings(settings)
|
||||||
|
player.setCrossfadeSeconds(value)
|
||||||
|
_state.update { it.copy(crossfadeSeconds = value) }
|
||||||
|
}
|
||||||
|
|
||||||
fun selectSearchMood(moodId: String) {
|
fun selectSearchMood(moodId: String) {
|
||||||
_state.update { it.copy(searchTargetMoodId = moodId) }
|
_state.update { it.copy(searchTargetMoodId = moodId) }
|
||||||
loadSearchTarget(moodId)
|
loadSearchTarget(moodId)
|
||||||
@@ -620,11 +739,16 @@ class AppStore(
|
|||||||
scope.launch {
|
scope.launch {
|
||||||
try {
|
try {
|
||||||
api.deleteMood(id)
|
api.deleteMood(id)
|
||||||
|
if (id in settings.offlineMoods) {
|
||||||
|
settings = settings.copy(offlineMoods = settings.offlineMoods - id)
|
||||||
|
cache.saveSettings(settings)
|
||||||
|
}
|
||||||
_state.update {
|
_state.update {
|
||||||
it.copy(
|
it.copy(
|
||||||
screen = Screen.Moods,
|
screen = Screen.Moods,
|
||||||
selectedMood = null,
|
selectedMood = null,
|
||||||
moods = it.moods.filterNot { mood -> mood.id == id },
|
moods = it.moods.filterNot { mood -> mood.id == id },
|
||||||
|
offlineMoods = settings.offlineMoods,
|
||||||
message = "Mood deleted",
|
message = "Mood deleted",
|
||||||
messageIsError = false,
|
messageIsError = false,
|
||||||
messageId = it.messageId + 1,
|
messageId = it.messageId + 1,
|
||||||
@@ -777,13 +901,11 @@ class AppStore(
|
|||||||
_state.update {
|
_state.update {
|
||||||
it.copy(
|
it.copy(
|
||||||
session = session,
|
session = session,
|
||||||
queue = session.queue,
|
|
||||||
offline = false,
|
offline = false,
|
||||||
screen = Screen.MoodDetail,
|
screen = Screen.MoodDetail,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
playNext()
|
setPlaybackTimeline(session.queue, 0)
|
||||||
persistPlayback()
|
|
||||||
} catch (t: Throwable) {
|
} catch (t: Throwable) {
|
||||||
val fallback = detail?.songs
|
val fallback = detail?.songs
|
||||||
?.map { it.song }
|
?.map { it.song }
|
||||||
@@ -793,14 +915,13 @@ class AppStore(
|
|||||||
_state.update {
|
_state.update {
|
||||||
it.copy(
|
it.copy(
|
||||||
session = null,
|
session = null,
|
||||||
queue = fallback.shuffled(Random.Default),
|
|
||||||
offline = true,
|
offline = true,
|
||||||
message = "Server unreachable, playing downloads",
|
message = "Server unreachable, playing downloads",
|
||||||
messageIsError = true,
|
messageIsError = true,
|
||||||
messageId = it.messageId + 1,
|
messageId = it.messageId + 1,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
playNext()
|
setPlaybackTimeline(fallback.shuffled(Random.Default), 0)
|
||||||
scheduleReconnect()
|
scheduleReconnect()
|
||||||
} else {
|
} else {
|
||||||
message(t)
|
message(t)
|
||||||
@@ -814,74 +935,104 @@ class AppStore(
|
|||||||
scope.launch {
|
scope.launch {
|
||||||
_state.value.session?.let { api.closeSession(it.id) }
|
_state.value.session?.let { api.closeSession(it.id) }
|
||||||
mergeSongs(listOf(song))
|
mergeSongs(listOf(song))
|
||||||
_state.update {
|
_state.update { it.copy(session = null) }
|
||||||
it.copy(
|
setPlaybackTimeline(listOf(song), 0)
|
||||||
session = null,
|
|
||||||
queue = emptyList(),
|
|
||||||
current = song,
|
|
||||||
history = pushHistory(it.history, it.current),
|
|
||||||
playing = true,
|
|
||||||
positionSeconds = 0.0,
|
|
||||||
durationSeconds = song.duration.toDouble(),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
persistPlayback()
|
|
||||||
startSong(song)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun moveInQueue(fromIndex: Int, toIndex: Int) {
|
fun moveInQueue(fromIndex: Int, toIndex: Int) {
|
||||||
_state.update { state ->
|
val queue = _state.value.queue
|
||||||
if (fromIndex !in state.queue.indices || toIndex !in state.queue.indices || fromIndex == toIndex) {
|
if (fromIndex !in queue.indices || toIndex !in queue.indices || fromIndex == toIndex) return
|
||||||
state
|
val base = trackIndex + 1
|
||||||
} else {
|
runCatching { player.moveInQueue(base + fromIndex, base + toIndex) }
|
||||||
val queue = state.queue.toMutableList()
|
.onFailure { message(it); return }
|
||||||
val item = queue.removeAt(fromIndex)
|
val moved = timelineSongs.toMutableList()
|
||||||
queue.add(toIndex, item)
|
val item = moved.removeAt(base + fromIndex)
|
||||||
state.copy(queue = queue)
|
moved.add(base + toIndex, item)
|
||||||
}
|
timelineSongs = moved
|
||||||
}
|
applyTimelineState()
|
||||||
persistPlayback()
|
persistPlayback()
|
||||||
}
|
}
|
||||||
|
|
||||||
fun removeFromQueue(index: Int) {
|
fun removeFromQueue(index: Int) {
|
||||||
_state.update { state ->
|
if (index !in _state.value.queue.indices) return
|
||||||
if (index !in state.queue.indices) {
|
val timelineIndex = trackIndex + 1 + index
|
||||||
state
|
runCatching { player.removeAt(timelineIndex) }
|
||||||
} else {
|
.onFailure { message(it); return }
|
||||||
state.copy(queue = state.queue.filterIndexed { i, _ -> i != index })
|
timelineSongs = timelineSongs.filterIndexed { i, _ -> i != timelineIndex }
|
||||||
}
|
applyTimelineState()
|
||||||
}
|
|
||||||
persistPlayback()
|
persistPlayback()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Plays an entry shown in the Up next list. */
|
||||||
|
fun playFromQueue(index: Int) {
|
||||||
|
if (index !in _state.value.queue.indices) return
|
||||||
|
player.playIndex(trackIndex + 1 + index)
|
||||||
|
syncTimelineNow()
|
||||||
|
startPolling()
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Pauses playback after [minutes] so the app does not keep playing while
|
* Pauses playback after [minutes] so the app does not keep playing while
|
||||||
* falling asleep. Passing null turns the timer off.
|
* falling asleep. Passing null turns the timer off.
|
||||||
*/
|
*/
|
||||||
fun setSleepTimer(minutes: Int?) {
|
fun setSleepTimer(minutes: Int?) {
|
||||||
sleepJob?.cancel()
|
setSleepCountdown(minutes?.takeIf { it > 0 }?.times(60L), atTrackEnd = false)
|
||||||
sleepJob = null
|
}
|
||||||
if (minutes == null || minutes <= 0) {
|
|
||||||
player.scheduleSleepTimer(null)
|
/** Stops when the current track ends, without cutting it in the middle. */
|
||||||
_state.update { it.copy(sleepTimerRemainingSeconds = null) }
|
fun setSleepAfterTrack() {
|
||||||
|
val state = _state.value
|
||||||
|
if (state.current == null) return
|
||||||
|
val remaining = (state.durationSeconds - state.positionSeconds)
|
||||||
|
.coerceAtLeast(0.0)
|
||||||
|
.let { kotlin.math.ceil(it).toLong() }
|
||||||
|
if (remaining <= 0) {
|
||||||
|
player.pause()
|
||||||
|
_state.update { it.copy(playing = false) }
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
setSleepCountdown(remaining, atTrackEnd = true)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun setSleepCountdown(seconds: Long?, atTrackEnd: Boolean) {
|
||||||
|
sleepJob?.cancel()
|
||||||
|
sleepJob = null
|
||||||
|
if (seconds == null || seconds <= 0) {
|
||||||
|
player.scheduleSleepTimer(null)
|
||||||
|
_state.update {
|
||||||
|
it.copy(sleepTimerRemainingSeconds = null, sleepAtTrackEnd = false)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
val total: Long = seconds
|
||||||
|
|
||||||
// Android hands the pause to the media service so it survives the UI
|
// Android hands the pause to the media service so it survives the UI
|
||||||
// being backgrounded or swiped away; the countdown below only drives
|
// being backgrounded or swiped away; the countdown below only drives
|
||||||
// the display and desktop/web playback.
|
// the display and desktop/web playback.
|
||||||
player.scheduleSleepTimer(minutes * 60L)
|
player.scheduleSleepTimer(total)
|
||||||
var remaining = minutes * 60L
|
var remaining: Long = total
|
||||||
_state.update { it.copy(sleepTimerRemainingSeconds = remaining) }
|
_state.update {
|
||||||
|
it.copy(
|
||||||
|
sleepTimerRemainingSeconds = remaining,
|
||||||
|
sleepAtTrackEnd = atTrackEnd,
|
||||||
|
)
|
||||||
|
}
|
||||||
sleepJob = scope.launch {
|
sleepJob = scope.launch {
|
||||||
while (isActive && remaining > 0) {
|
while (isActive && remaining > 0) {
|
||||||
delay(1_000)
|
delay(1_000)
|
||||||
remaining -= 1
|
remaining -= 1
|
||||||
val seconds = remaining.coerceAtLeast(0)
|
val value = remaining.coerceAtLeast(0)
|
||||||
_state.update { it.copy(sleepTimerRemainingSeconds = seconds.takeIf { value -> value > 0 }) }
|
_state.update {
|
||||||
|
it.copy(sleepTimerRemainingSeconds = value.takeIf { seconds -> seconds > 0 })
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (!isActive) return@launch
|
if (!isActive) return@launch
|
||||||
|
endSleepTimer()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun endSleepTimer() {
|
||||||
val wasPlaying = _state.value.playing
|
val wasPlaying = _state.value.playing
|
||||||
player.pause()
|
player.pause()
|
||||||
pollJob?.cancel()
|
pollJob?.cancel()
|
||||||
@@ -890,95 +1041,66 @@ class AppStore(
|
|||||||
it.copy(
|
it.copy(
|
||||||
playing = false,
|
playing = false,
|
||||||
sleepTimerRemainingSeconds = null,
|
sleepTimerRemainingSeconds = null,
|
||||||
|
sleepAtTrackEnd = false,
|
||||||
message = if (wasPlaying) "Sleep timer: playback paused" else null,
|
message = if (wasPlaying) "Sleep timer: playback paused" else null,
|
||||||
messageId = if (wasPlaying) it.messageId + 1 else it.messageId,
|
messageId = if (wasPlaying) it.messageId + 1 else it.messageId,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
fun togglePlayPause() {
|
fun togglePlayPause() {
|
||||||
val state = _state.value
|
val state = _state.value
|
||||||
val song = state.current ?: return
|
if (state.current == null && timelineSongs.isEmpty()) return
|
||||||
if (state.playing) {
|
if (state.playing) {
|
||||||
player.pause()
|
player.pause()
|
||||||
pollJob?.cancel()
|
pollJob?.cancel()
|
||||||
_state.update { it.copy(playing = false) }
|
_state.update { it.copy(playing = false) }
|
||||||
persistPlayback()
|
persistPlayback()
|
||||||
} else if (!playbackStarted || player.isFinished()) {
|
return
|
||||||
val finished = player.isFinished()
|
|
||||||
val duration = state.durationSeconds.takeIf { it > 0 } ?: song.duration.toDouble()
|
|
||||||
val startAt = if (finished || (duration > 0 && state.positionSeconds >= duration - 1.0)) {
|
|
||||||
0.0
|
|
||||||
} else {
|
|
||||||
state.positionSeconds.coerceAtLeast(0.0)
|
|
||||||
}
|
}
|
||||||
_state.update {
|
|
||||||
it.copy(
|
val startAt = state.positionSeconds
|
||||||
playing = true,
|
.takeIf { !player.isFinished() && it < state.durationSeconds - 1.0 }
|
||||||
positionSeconds = startAt,
|
?.coerceAtLeast(0.0)
|
||||||
durationSeconds = duration,
|
?: 0.0
|
||||||
)
|
if (!playbackStarted || player.queueSize() == 0) {
|
||||||
|
val songs = timelineSongs.ifEmpty { listOfNotNull(state.current) }
|
||||||
|
if (songs.isEmpty()) return
|
||||||
|
setPlaybackTimeline(songs, trackIndex.coerceIn(songs.indices), startAt)
|
||||||
|
return
|
||||||
}
|
}
|
||||||
startSong(song, startAt)
|
if (player.isFinished()) {
|
||||||
|
player.playIndex(trackIndex, startAt)
|
||||||
} else {
|
} else {
|
||||||
player.resume()
|
player.resume()
|
||||||
_state.update { it.copy(playing = true) }
|
|
||||||
startPolling()
|
|
||||||
}
|
}
|
||||||
|
_state.update { it.copy(playing = true, positionSeconds = startAt) }
|
||||||
|
startPolling()
|
||||||
}
|
}
|
||||||
|
|
||||||
fun skip() {
|
fun skip() {
|
||||||
val state = _state.value
|
val state = _state.value
|
||||||
state.current?.let { report("skipped", it.id, state.positionSeconds.toInt()) }
|
state.current?.let { report("skipped", it.id, state.positionSeconds.toInt()) }
|
||||||
playNext()
|
suppressCompletion = true
|
||||||
|
if (trackIndex + 1 >= timelineSongs.size && state.session != null) {
|
||||||
|
fetchMoreThenSkip()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
player.skipToNext()
|
||||||
|
syncTimelineNow()
|
||||||
|
startPolling()
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Back button semantics: after two seconds of playback the current track
|
* Back button semantics: after two seconds of playback the current track
|
||||||
* restarts, otherwise the previous track is restored. The outgoing track is
|
* restarts, otherwise the previous track is restored.
|
||||||
* put back at the front of the queue so nothing is lost.
|
|
||||||
*/
|
*/
|
||||||
fun previous() {
|
fun previous() {
|
||||||
val state = _state.value
|
if (_state.value.current == null) return
|
||||||
val song = state.current ?: return
|
suppressCompletion = true
|
||||||
val elapsed = (state.positionSeconds - trackStartOffset).coerceAtLeast(0.0)
|
player.skipToPrevious(2.0)
|
||||||
if (elapsed > 2.0) {
|
syncTimelineNow()
|
||||||
restartCurrent(song)
|
startPolling()
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
val target = state.history.lastOrNull()
|
|
||||||
if (target == null) {
|
|
||||||
restartCurrent(song)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
_state.update {
|
|
||||||
it.copy(
|
|
||||||
history = it.history.dropLast(1),
|
|
||||||
queue = listOf(song) + it.queue,
|
|
||||||
current = target,
|
|
||||||
playing = true,
|
|
||||||
positionSeconds = 0.0,
|
|
||||||
durationSeconds = target.duration.toDouble(),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
persistPlayback()
|
|
||||||
startSong(target)
|
|
||||||
report("started", target.id, 0)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun restartCurrent(song: Song) {
|
|
||||||
trackStartOffset = 0.0
|
|
||||||
if (player.canSeek) {
|
|
||||||
runCatching { player.seekTo(0.0) }
|
|
||||||
.onFailure { message(it) }
|
|
||||||
_state.update { it.copy(positionSeconds = 0.0) }
|
|
||||||
} else {
|
|
||||||
_state.update { it.copy(playing = true, positionSeconds = 0.0) }
|
|
||||||
startSong(song)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fun seekTo(seconds: Double) {
|
fun seekTo(seconds: Double) {
|
||||||
@@ -1046,7 +1168,16 @@ class AppStore(
|
|||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
downloadSong(song, announce = true)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Downloads a track for offline playback. Offline mood sync calls this
|
||||||
|
* quietly so a large mood does not produce one snackbar per song.
|
||||||
|
*/
|
||||||
|
private fun downloadSong(song: Song, announce: Boolean) {
|
||||||
|
val state = _state.value
|
||||||
|
if (song.id in state.downloads || song.id in state.downloading) return
|
||||||
val generation = dataGeneration
|
val generation = dataGeneration
|
||||||
scope.launch {
|
scope.launch {
|
||||||
_state.update { it.copy(downloading = it.downloading + song.id) }
|
_state.update { it.copy(downloading = it.downloading + song.id) }
|
||||||
@@ -1067,25 +1198,30 @@ class AppStore(
|
|||||||
return@launch
|
return@launch
|
||||||
}
|
}
|
||||||
if (path == null) {
|
if (path == null) {
|
||||||
|
offlineFailed += song.id
|
||||||
|
_state.update { it.copy(downloading = it.downloading - song.id) }
|
||||||
|
if (announce) {
|
||||||
_state.update {
|
_state.update {
|
||||||
it.copy(
|
it.copy(
|
||||||
downloading = it.downloading - song.id,
|
|
||||||
message = "Downloads are not available on this platform",
|
message = "Downloads are not available on this platform",
|
||||||
messageIsError = true,
|
messageIsError = true,
|
||||||
messageId = it.messageId + 1,
|
messageId = it.messageId + 1,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
return@launch
|
return@launch
|
||||||
}
|
}
|
||||||
_state.update {
|
_state.update {
|
||||||
it.copy(
|
it.copy(
|
||||||
downloading = it.downloading - song.id,
|
downloading = it.downloading - song.id,
|
||||||
downloads = storage.listDownloads().keys,
|
downloads = storage.listDownloads().keys,
|
||||||
message = "Downloaded ${song.title}",
|
message = if (announce) "Downloaded ${song.title}" else it.message,
|
||||||
messageIsError = false,
|
messageIsError = if (announce) false else it.messageIsError,
|
||||||
messageId = it.messageId + 1,
|
messageId = if (announce) it.messageId + 1 else it.messageId,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
offlineFailed -= song.id
|
||||||
|
syncOfflineMoods()
|
||||||
return@launch
|
return@launch
|
||||||
} catch (t: Throwable) {
|
} catch (t: Throwable) {
|
||||||
lastError = t
|
lastError = t
|
||||||
@@ -1100,9 +1236,47 @@ class AppStore(
|
|||||||
downloads = storage.listDownloads().keys,
|
downloads = storage.listDownloads().keys,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
lastError?.let { offlineFailed += song.id }
|
||||||
|
if (announce) {
|
||||||
message(lastError ?: IllegalStateException("Download failed"))
|
message(lastError ?: IllegalStateException("Download failed"))
|
||||||
|
} else {
|
||||||
|
lastError?.let { error ->
|
||||||
|
_state.update {
|
||||||
|
it.copy(
|
||||||
|
message = "Offline sync failed: ${error.friendlyMessage()}",
|
||||||
|
messageIsError = true,
|
||||||
|
messageId = it.messageId + 1,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
syncOfflineMoods()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Brings every mood marked offline in line with its current song list. */
|
||||||
|
private fun syncOfflineMoods() {
|
||||||
|
if (settings.offlineMoods.isEmpty()) return
|
||||||
|
if (!isUnmeteredNetwork()) return
|
||||||
|
val details = (cache.load().moodDetails + listOfNotNull(_state.value.selectedMood))
|
||||||
|
.distinctBy { it.mood.id }
|
||||||
|
val songs = details
|
||||||
|
.filter { it.mood.id in settings.offlineMoods }
|
||||||
|
.flatMap { detail -> detail.songs.map { it.song } }
|
||||||
|
// Keep a few downloads in flight rather than opening one request per
|
||||||
|
// mood song; each completion calls this function again.
|
||||||
|
val slots = (OFFLINE_PARALLEL - _state.value.downloading.size).coerceAtLeast(0)
|
||||||
|
if (slots == 0) return
|
||||||
|
songs.asSequence()
|
||||||
|
.filter {
|
||||||
|
it.id !in _state.value.downloads &&
|
||||||
|
it.id !in _state.value.downloading &&
|
||||||
|
it.id !in offlineFailed
|
||||||
|
}
|
||||||
|
.distinctBy { it.id }
|
||||||
|
.take(slots)
|
||||||
|
.forEach { song -> downloadSong(song, announce = false) }
|
||||||
|
}
|
||||||
|
|
||||||
fun clearDownloads() {
|
fun clearDownloads() {
|
||||||
storage.listDownloads().keys.forEach(storage::deleteDownload)
|
storage.listDownloads().keys.forEach(storage::deleteDownload)
|
||||||
@@ -1125,6 +1299,8 @@ class AppStore(
|
|||||||
|
|
||||||
fun canSeek(): Boolean = player.canSeek
|
fun canSeek(): Boolean = player.canSeek
|
||||||
|
|
||||||
|
fun supportsCrossfade(): Boolean = player.supportsCrossfade
|
||||||
|
|
||||||
fun clearMessage() {
|
fun clearMessage() {
|
||||||
_state.update { it.copy(message = null) }
|
_state.update { it.copy(message = null) }
|
||||||
}
|
}
|
||||||
@@ -1134,7 +1310,6 @@ class AppStore(
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun release() {
|
fun release() {
|
||||||
player.setSkipCallbacks(onNext = null, onPrevious = null)
|
|
||||||
persistPlayback()
|
persistPlayback()
|
||||||
pollJob?.cancel()
|
pollJob?.cancel()
|
||||||
refreshJob?.cancel()
|
refreshJob?.cancel()
|
||||||
@@ -1145,88 +1320,21 @@ class AppStore(
|
|||||||
api.close()
|
api.close()
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun playNext() {
|
private fun setPlaybackTimeline(
|
||||||
if (advancing) return
|
songs: List<Song>,
|
||||||
val state = _state.value
|
index: Int,
|
||||||
if (state.queue.isEmpty()) {
|
startAtSeconds: Double = 0.0,
|
||||||
val session = state.session
|
) {
|
||||||
if (session == null) {
|
if (songs.isEmpty()) return
|
||||||
_state.update { it.copy(playing = false) }
|
playbackGeneration += 1
|
||||||
return
|
|
||||||
}
|
|
||||||
advancing = true
|
|
||||||
val sessionId = session.id
|
|
||||||
scope.launch {
|
|
||||||
try {
|
|
||||||
val more = api.nextTracks(sessionId, 12)
|
|
||||||
mergeSongs(more)
|
|
||||||
if (_state.value.session?.id == sessionId) {
|
|
||||||
_state.update { it.copy(queue = it.queue + more) }
|
|
||||||
}
|
|
||||||
} catch (t: Throwable) {
|
|
||||||
message(t)
|
|
||||||
} finally {
|
|
||||||
advancing = false
|
|
||||||
}
|
|
||||||
if (_state.value.session?.id != sessionId) return@launch
|
|
||||||
if (_state.value.queue.isNotEmpty()) playNext() else _state.update { it.copy(playing = false) }
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
val song = state.queue.first()
|
|
||||||
_state.update {
|
|
||||||
it.copy(
|
|
||||||
queue = it.queue.drop(1),
|
|
||||||
current = song,
|
|
||||||
history = pushHistory(it.history, it.current),
|
|
||||||
playing = true,
|
|
||||||
positionSeconds = 0.0,
|
|
||||||
durationSeconds = song.duration.toDouble(),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
persistPlayback()
|
|
||||||
startSong(song)
|
|
||||||
report("started", song.id, 0)
|
|
||||||
if (_state.value.queue.size < 3) prefetch()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun prefetch() {
|
|
||||||
val session = _state.value.session ?: return
|
|
||||||
if (fetching) return
|
|
||||||
fetching = true
|
|
||||||
val sessionId = session.id
|
|
||||||
scope.launch {
|
|
||||||
try {
|
|
||||||
val more = api.nextTracks(sessionId, 12)
|
|
||||||
mergeSongs(more)
|
|
||||||
if (_state.value.session?.id == sessionId) {
|
|
||||||
_state.update { it.copy(queue = it.queue + more) }
|
|
||||||
}
|
|
||||||
} catch (_: Throwable) {
|
|
||||||
// The queue still has tracks; a later request will retry.
|
|
||||||
} finally {
|
|
||||||
fetching = false
|
fetching = false
|
||||||
}
|
suppressCompletion = false
|
||||||
}
|
timelineSongs = songs
|
||||||
}
|
trackIndex = index.coerceIn(songs.indices)
|
||||||
|
applyTimelineState()
|
||||||
private fun startSong(song: Song, startAtSeconds: Double = 0.0) {
|
val tracks = buildTracks(songs)
|
||||||
val localPath = storage.downloadPath(song.id)
|
|
||||||
finishing = false
|
|
||||||
pollTicks = 0
|
|
||||||
trackStartOffset = startAtSeconds
|
|
||||||
try {
|
try {
|
||||||
player.play(
|
player.setQueue(tracks, trackIndex, startAtSeconds)
|
||||||
source = localPath ?: api.streamUrl(song.id),
|
|
||||||
song = song,
|
|
||||||
local = localPath != null,
|
|
||||||
artworkUri = api.coverUrl(song.id),
|
|
||||||
artworkBytes = storage.artworkBytes(song.id),
|
|
||||||
)
|
|
||||||
if (startAtSeconds > 0 && player.canSeek) {
|
|
||||||
player.seekTo(startAtSeconds)
|
|
||||||
}
|
|
||||||
} catch (t: Throwable) {
|
} catch (t: Throwable) {
|
||||||
_state.update {
|
_state.update {
|
||||||
it.copy(
|
it.copy(
|
||||||
@@ -1239,7 +1347,113 @@ class AppStore(
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
playbackStarted = true
|
playbackStarted = true
|
||||||
|
pollTicks = 0
|
||||||
|
_state.update {
|
||||||
|
it.copy(playing = true, positionSeconds = startAtSeconds.coerceAtLeast(0.0))
|
||||||
|
}
|
||||||
startPolling()
|
startPolling()
|
||||||
|
persistPlayback()
|
||||||
|
report("started", timelineSongs.getOrNull(trackIndex)?.id, startAtSeconds.toInt())
|
||||||
|
if (_state.value.queue.size < 3) prefetch()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun buildTracks(songs: List<Song>): List<PlaybackTrack> = songs.map { song ->
|
||||||
|
val local = storage.downloadPath(song.id)
|
||||||
|
PlaybackTrack(
|
||||||
|
song = song,
|
||||||
|
source = local ?: api.streamUrl(song.id),
|
||||||
|
local = local != null,
|
||||||
|
artworkUri = api.coverUrl(song.id),
|
||||||
|
gainDb = if (_state.value.normalizationEnabled) song.gainDb else null,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Applies store-initiated transport changes without waiting for a poll. */
|
||||||
|
private fun syncTimelineNow() {
|
||||||
|
val index = player.currentIndex()
|
||||||
|
if (index !in timelineSongs.indices) return
|
||||||
|
if (index != trackIndex) {
|
||||||
|
val outgoing = timelineSongs.getOrNull(trackIndex)
|
||||||
|
if (outgoing != null && !suppressCompletion) {
|
||||||
|
report("completed", outgoing.id, _state.value.positionSeconds.toInt())
|
||||||
|
}
|
||||||
|
suppressCompletion = false
|
||||||
|
trackIndex = index
|
||||||
|
report("started", timelineSongs.getOrNull(index)?.id, 0)
|
||||||
|
}
|
||||||
|
applyTimelineState()
|
||||||
|
_state.update {
|
||||||
|
it.copy(
|
||||||
|
playing = player.isPlaying(),
|
||||||
|
positionSeconds = player.positionSeconds().coerceAtLeast(0.0),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun applyTimelineState() {
|
||||||
|
val index = trackIndex.coerceIn(0, (timelineSongs.size - 1).coerceAtLeast(0))
|
||||||
|
val current = timelineSongs.getOrNull(index)
|
||||||
|
_state.update {
|
||||||
|
it.copy(
|
||||||
|
current = current,
|
||||||
|
queue = timelineSongs.drop(index + 1),
|
||||||
|
history = timelineSongs.take(index),
|
||||||
|
durationSeconds = player.durationSeconds().takeIf { value -> value > 0 }
|
||||||
|
?: current?.duration?.toDouble()
|
||||||
|
?: it.durationSeconds,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun fetchMoreThenSkip() {
|
||||||
|
val state = _state.value
|
||||||
|
val session = state.session ?: return
|
||||||
|
val generation = playbackGeneration
|
||||||
|
scope.launch {
|
||||||
|
try {
|
||||||
|
val more = api.nextTracks(session.id, 12)
|
||||||
|
if (generation != playbackGeneration || _state.value.session?.id != session.id) return@launch
|
||||||
|
if (more.isEmpty()) {
|
||||||
|
player.skipToNext()
|
||||||
|
return@launch
|
||||||
|
}
|
||||||
|
mergeSongs(more)
|
||||||
|
timelineSongs = timelineSongs + more
|
||||||
|
player.appendToQueue(buildTracks(more))
|
||||||
|
_state.update { it.copy(queue = it.queue + more) }
|
||||||
|
player.skipToNext()
|
||||||
|
startPolling()
|
||||||
|
} catch (t: Throwable) {
|
||||||
|
message(t)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun prefetch() {
|
||||||
|
val session = _state.value.session ?: return
|
||||||
|
if (fetching) return
|
||||||
|
fetching = true
|
||||||
|
val sessionId = session.id
|
||||||
|
val generation = playbackGeneration
|
||||||
|
scope.launch {
|
||||||
|
try {
|
||||||
|
val more = api.nextTracks(sessionId, 12)
|
||||||
|
if (generation != playbackGeneration ||
|
||||||
|
_state.value.session?.id != sessionId ||
|
||||||
|
more.isEmpty()
|
||||||
|
) {
|
||||||
|
return@launch
|
||||||
|
}
|
||||||
|
mergeSongs(more)
|
||||||
|
timelineSongs = timelineSongs + more
|
||||||
|
player.appendToQueue(buildTracks(more))
|
||||||
|
_state.update { it.copy(queue = it.queue + more) }
|
||||||
|
} catch (_: Throwable) {
|
||||||
|
// The queue still has tracks; a later request will retry.
|
||||||
|
} finally {
|
||||||
|
fetching = false
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun startPolling() {
|
private fun startPolling() {
|
||||||
@@ -1247,11 +1461,25 @@ class AppStore(
|
|||||||
pollJob = scope.launch {
|
pollJob = scope.launch {
|
||||||
while (isActive && _state.value.current != null) {
|
while (isActive && _state.value.current != null) {
|
||||||
delay(400)
|
delay(400)
|
||||||
val state = _state.value
|
val index = player.currentIndex()
|
||||||
|
if (index != trackIndex && index in timelineSongs.indices) {
|
||||||
|
val outgoing = timelineSongs.getOrNull(trackIndex)
|
||||||
|
if (outgoing != null && !suppressCompletion) {
|
||||||
|
report("completed", outgoing.id, _state.value.positionSeconds.toInt())
|
||||||
|
}
|
||||||
|
suppressCompletion = false
|
||||||
|
trackIndex = index
|
||||||
|
report("started", timelineSongs.getOrNull(index)?.id, 0)
|
||||||
|
}
|
||||||
val position = player.positionSeconds()
|
val position = player.positionSeconds()
|
||||||
val duration = player.durationSeconds().takeIf { it > 0 } ?: state.durationSeconds
|
val duration = player.durationSeconds().takeIf { it > 0 }
|
||||||
|
?: timelineSongs.getOrNull(trackIndex)?.duration?.toDouble()
|
||||||
|
?: _state.value.durationSeconds
|
||||||
_state.update {
|
_state.update {
|
||||||
it.copy(
|
it.copy(
|
||||||
|
current = timelineSongs.getOrNull(trackIndex) ?: it.current,
|
||||||
|
queue = timelineSongs.drop(trackIndex + 1),
|
||||||
|
history = timelineSongs.take(trackIndex),
|
||||||
positionSeconds = position.coerceAtLeast(0.0),
|
positionSeconds = position.coerceAtLeast(0.0),
|
||||||
durationSeconds = duration,
|
durationSeconds = duration,
|
||||||
playing = player.isPlaying(),
|
playing = player.isPlaying(),
|
||||||
@@ -1264,16 +1492,64 @@ class AppStore(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (player.isFinished()) {
|
if (player.isFinished()) {
|
||||||
if (!finishing) {
|
if (!advanceAtEnd()) break
|
||||||
finishing = true
|
} else if (_state.value.queue.size < 3) {
|
||||||
report("completed", state.current?.id, state.positionSeconds.toInt())
|
prefetch()
|
||||||
playNext()
|
|
||||||
}
|
|
||||||
break
|
|
||||||
}
|
|
||||||
if (state.current == null) break
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
pollJob = null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Returns false when playback should stop at the end of the timeline. */
|
||||||
|
private suspend fun advanceAtEnd(): Boolean {
|
||||||
|
// A prefetch may already have appended the next batch while ExoPlayer
|
||||||
|
// was finishing. Play it instead of requesting duplicates.
|
||||||
|
if (trackIndex + 1 < timelineSongs.size) {
|
||||||
|
player.playIndex(trackIndex + 1)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if (fetching) {
|
||||||
|
delay(500)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if (_state.value.sleepAtTrackEnd) {
|
||||||
|
sleepJob?.cancel()
|
||||||
|
sleepJob = null
|
||||||
|
player.scheduleSleepTimer(null)
|
||||||
|
player.pause()
|
||||||
|
_state.update {
|
||||||
|
it.copy(
|
||||||
|
playing = false,
|
||||||
|
sleepAtTrackEnd = false,
|
||||||
|
sleepTimerRemainingSeconds = null,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
val session = _state.value.session
|
||||||
|
val current = timelineSongs.getOrNull(trackIndex)
|
||||||
|
if (session == null) {
|
||||||
|
_state.update { it.copy(playing = false) }
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
val generation = playbackGeneration
|
||||||
|
val more = runCatching { api.nextTracks(session.id, 12) }.getOrNull().orEmpty()
|
||||||
|
if (generation != playbackGeneration || _state.value.session?.id != session.id) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if (more.isEmpty()) {
|
||||||
|
_state.update { it.copy(playing = false) }
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
mergeSongs(more)
|
||||||
|
val from = timelineSongs.size
|
||||||
|
timelineSongs = timelineSongs + more
|
||||||
|
player.appendToQueue(buildTracks(more))
|
||||||
|
applyTimelineState()
|
||||||
|
_state.update { it.copy(playing = true) }
|
||||||
|
player.playIndex(from)
|
||||||
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun report(type: String, songId: String?, positionSeconds: Int) {
|
private fun report(type: String, songId: String?, positionSeconds: Int) {
|
||||||
@@ -1295,10 +1571,13 @@ class AppStore(
|
|||||||
|
|
||||||
private fun stopPlayback() {
|
private fun stopPlayback() {
|
||||||
pollJob?.cancel()
|
pollJob?.cancel()
|
||||||
|
pollJob = null
|
||||||
sleepJob?.cancel()
|
sleepJob?.cancel()
|
||||||
sleepJob = null
|
sleepJob = null
|
||||||
reconnectJob?.cancel()
|
reconnectJob?.cancel()
|
||||||
playbackStarted = false
|
playbackStarted = false
|
||||||
|
timelineSongs = emptyList()
|
||||||
|
trackIndex = 0
|
||||||
player.scheduleSleepTimer(null)
|
player.scheduleSleepTimer(null)
|
||||||
player.stop()
|
player.stop()
|
||||||
_state.update {
|
_state.update {
|
||||||
@@ -1309,6 +1588,7 @@ class AppStore(
|
|||||||
queue = emptyList(),
|
queue = emptyList(),
|
||||||
session = null,
|
session = null,
|
||||||
sleepTimerRemainingSeconds = null,
|
sleepTimerRemainingSeconds = null,
|
||||||
|
sleepAtTrackEnd = false,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
cache.savePlayback(null)
|
cache.savePlayback(null)
|
||||||
@@ -1347,6 +1627,7 @@ class AppStore(
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
syncOfflineMoods()
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun mergeSongs(songs: Collection<Song>) {
|
private fun mergeSongs(songs: Collection<Song>) {
|
||||||
@@ -1452,6 +1733,7 @@ private const val RECONNECT_MAX_MS = 300_000L
|
|||||||
private const val DOWNLOAD_ATTEMPTS = 3
|
private const val DOWNLOAD_ATTEMPTS = 3
|
||||||
private const val PROGRESS_POLL_TICKS = 12
|
private const val PROGRESS_POLL_TICKS = 12
|
||||||
private const val MAX_HISTORY = 50
|
private const val MAX_HISTORY = 50
|
||||||
|
private const val OFFLINE_PARALLEL = 3
|
||||||
private const val SEARCH_DEBOUNCE_MS = 300L
|
private const val SEARCH_DEBOUNCE_MS = 300L
|
||||||
private const val SEARCH_LIMIT = 10
|
private const val SEARCH_LIMIT = 10
|
||||||
private const val DEFAULT_SOURCE = "deezer"
|
private const val DEFAULT_SOURCE = "deezer"
|
||||||
|
|||||||
@@ -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") }
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
+7
-146
@@ -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,6 +175,11 @@ 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))
|
||||||
|
Text("Settings")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -232,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)) }
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+348
@@ -0,0 +1,348 @@
|
|||||||
|
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
|
||||||
|
|
||||||
|
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(
|
||||||
|
"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") }
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
+353
@@ -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 = {
|
||||||
@@ -147,31 +149,13 @@ fun PlayerBar(state: AppState, store: AppStore) {
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
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)
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Row(
|
Row(
|
||||||
@@ -180,6 +164,13 @@ fun PlayerBar(state: AppState, store: AppStore) {
|
|||||||
.padding(start = 12.dp, end = 8.dp, bottom = 8.dp),
|
.padding(start = 12.dp, end = 8.dp, bottom = 8.dp),
|
||||||
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)) {
|
||||||
@@ -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) }
|
||||||
|
|||||||
+87
-1
@@ -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.3 · $platformName",
|
"AudioManager 0.4.0 · $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)
|
||||||
@@ -417,6 +418,68 @@ 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
|
@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()
|
||||||
@@ -529,22 +592,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
|
||||||
@@ -552,25 +599,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
|
||||||
@@ -588,12 +689,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() }
|
||||||
}
|
}
|
||||||
+86
-27
@@ -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, 2f) ?: 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()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user