mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-21 05:46:03 +00:00
feat: Add Soundtracks tab and music player (#2389)
This commit is contained in:
1 parent
33dbd8755f
commit
d33f4b4896
78 files changed
+5618
-64
No files matched your search
@@ -0,0 +1,288 @@
|
||||
package com.droiddeck.launcher.playback
|
||||
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.os.Bundle
|
||||
import android.net.Uri
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableLongStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.media3.common.MediaItem
|
||||
import androidx.media3.common.MediaMetadata
|
||||
import androidx.media3.common.PlaybackParameters
|
||||
import androidx.media3.common.Player
|
||||
import androidx.media3.session.MediaController
|
||||
import androidx.media3.session.SessionToken
|
||||
import com.droiddeck.launcher.frontend.Soundtrack
|
||||
import com.google.common.util.concurrent.ListenableFuture
|
||||
import java.io.File
|
||||
|
||||
object SoundtrackController {
|
||||
var playing by mutableStateOf(false)
|
||||
private set
|
||||
var currentId by mutableStateOf<String?>(null)
|
||||
private set
|
||||
var title by mutableStateOf("")
|
||||
private set
|
||||
var shuffle by mutableStateOf(false)
|
||||
private set
|
||||
var repeat by mutableStateOf(Player.REPEAT_MODE_OFF)
|
||||
private set
|
||||
var durationMs by mutableStateOf(0L)
|
||||
private set
|
||||
var buffering by mutableStateOf(false)
|
||||
private set
|
||||
var volume by mutableStateOf(1f)
|
||||
private set
|
||||
|
||||
var activeCollection by mutableStateOf<Int?>(null)
|
||||
private set
|
||||
|
||||
var sleepEndsAt by mutableLongStateOf(0L)
|
||||
private set
|
||||
var sleepTrackEnd by mutableStateOf(false)
|
||||
private set
|
||||
|
||||
private var app: Context? = null
|
||||
private val removed: MutableSet<String> = java.util.Collections.synchronizedSet(HashSet())
|
||||
private var activeRoot: String? = null
|
||||
private var savedId: String? = null
|
||||
private var future: ListenableFuture<MediaController>? = null
|
||||
private var controller: MediaController? = null
|
||||
private val pending = ArrayList<(MediaController) -> Unit>()
|
||||
|
||||
private val listener = object : Player.Listener {
|
||||
override fun onEvents(player: Player, events: Player.Events) = sync(player)
|
||||
}
|
||||
|
||||
private val disconnect = object : MediaController.Listener {
|
||||
override fun onDisconnected(controller: MediaController) {
|
||||
if (this@SoundtrackController.controller === controller) {
|
||||
this@SoundtrackController.controller = null
|
||||
future = null
|
||||
reset()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun reset() {
|
||||
playing = false
|
||||
currentId = null
|
||||
title = ""
|
||||
durationMs = 0L
|
||||
buffering = false
|
||||
volume = 1f
|
||||
activeCollection = null
|
||||
}
|
||||
|
||||
private fun sync(player: Player) {
|
||||
playing = player.isPlaying
|
||||
buffering = player.playbackState == Player.STATE_BUFFERING
|
||||
currentId = player.currentMediaItem?.mediaId?.takeIf { player.mediaItemCount > 0 }
|
||||
title = player.mediaMetadata.title?.toString().orEmpty()
|
||||
shuffle = player.shuffleModeEnabled
|
||||
repeat = player.repeatMode
|
||||
durationMs = player.duration.takeIf { it > 0 } ?: 0L
|
||||
volume = player.volume
|
||||
if (!player.playWhenReady) sleepTrackEnd = false
|
||||
persistResume(player)
|
||||
}
|
||||
|
||||
private fun persistResume(player: Player) {
|
||||
val context = app ?: return
|
||||
val id = currentId ?: return
|
||||
if (activeCollection != null) return
|
||||
val root = activeRoot ?: SoundtrackSettings.resume(context)?.root?.takeIf { id.startsWith("$it/") }?.also { activeRoot = it } ?: return
|
||||
if (id != savedId || !player.isPlaying) {
|
||||
savedId = id
|
||||
SoundtrackSettings.saveResume(context, root, id, if (player.playbackState == Player.STATE_ENDED) 0L else player.currentPosition)
|
||||
}
|
||||
}
|
||||
|
||||
private fun applySettings(c: MediaController) {
|
||||
val context = app ?: return
|
||||
SoundtrackSettings.load(context)
|
||||
c.setPlaybackParameters(PlaybackParameters(SoundtrackSettings.speed, SoundtrackSettings.pitch))
|
||||
c.sendCustomCommand(SoundtrackService.SKIP_SILENCE, Bundle().apply { putBoolean(SoundtrackService.ARG_ON, SoundtrackSettings.skipSilence) })
|
||||
sendEqualizer(c)
|
||||
c.sendCustomCommand(SoundtrackService.INGAME, Bundle().apply { putBoolean(SoundtrackService.ARG_ON, com.droiddeck.launcher.session.SessionPrefs.soundtracksIngame(context)) })
|
||||
}
|
||||
|
||||
private fun sendEqualizer(c: MediaController) {
|
||||
c.sendCustomCommand(
|
||||
SoundtrackService.EQUALIZER,
|
||||
Bundle().apply {
|
||||
putBoolean(SoundtrackService.ARG_ON, SoundtrackSettings.eqOn)
|
||||
putIntArray(SoundtrackService.ARG_BANDS, SoundtrackSettings.bands.toIntArray())
|
||||
putInt(SoundtrackService.ARG_BASS, SoundtrackSettings.bass)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
private fun run(context: Context, block: (MediaController) -> Unit) {
|
||||
app = context.applicationContext
|
||||
val live = controller
|
||||
if (live != null) { block(live); return }
|
||||
pending += block
|
||||
if (future != null) return
|
||||
val app = context.applicationContext
|
||||
val token = SessionToken(app, ComponentName(app, SoundtrackService::class.java))
|
||||
val built = MediaController.Builder(app, token).setListener(disconnect)
|
||||
.setConnectionHints(Bundle().apply { putBoolean(SoundtrackService.HINT_OWNER, true) }).buildAsync()
|
||||
future = built
|
||||
built.addListener({
|
||||
val ready = runCatching { built.get() }.getOrNull()
|
||||
if (ready == null) {
|
||||
future = null
|
||||
pending.clear()
|
||||
return@addListener
|
||||
}
|
||||
controller = ready
|
||||
ready.addListener(listener)
|
||||
applySettings(ready)
|
||||
sync(ready)
|
||||
val queued = pending.toList()
|
||||
pending.clear()
|
||||
queued.forEach { it(ready) }
|
||||
}, ContextCompat.getMainExecutor(app))
|
||||
}
|
||||
|
||||
fun connect(context: Context) = run(context) { }
|
||||
|
||||
fun position(): Long = controller?.currentPosition ?: 0L
|
||||
|
||||
fun belongsCollection(id: Int): Boolean = activeCollection == id && currentId != null
|
||||
|
||||
fun belongs(root: File?): Boolean {
|
||||
if (activeCollection != null) return false
|
||||
val id = currentId ?: return false
|
||||
return root != null && id.startsWith(root.path + "/")
|
||||
}
|
||||
|
||||
private fun items(album: Soundtrack.Album, albumTitle: String): List<MediaItem> {
|
||||
val cover = album.cover?.let { Uri.fromFile(it) }
|
||||
return album.tracks.map { t ->
|
||||
MediaItem.Builder()
|
||||
.setMediaId(t.file.path)
|
||||
.setMediaMetadata(
|
||||
MediaMetadata.Builder()
|
||||
.setTitle(t.title)
|
||||
.setArtist(t.artist.ifBlank { album.artist }.ifBlank { null })
|
||||
.setAlbumTitle(albumTitle)
|
||||
.setTrackNumber(t.number)
|
||||
.setDiscNumber(t.disc.takeIf { it > 0 })
|
||||
.setArtworkUri(cover)
|
||||
.setIsPlayable(true)
|
||||
.build(),
|
||||
)
|
||||
.build()
|
||||
}
|
||||
}
|
||||
|
||||
fun play(
|
||||
context: Context, album: Soundtrack.Album, albumTitle: String, startId: String?, shuffled: Boolean? = null,
|
||||
root: File? = null, startMs: Long = 0L, collection: Int? = null,
|
||||
) {
|
||||
val list = items(album, albumTitle)
|
||||
if (list.isEmpty()) return
|
||||
run(context) { c ->
|
||||
if (root != null && root.path in removed) return@run
|
||||
val start = list.indexOfFirst { it.mediaId == startId }.coerceAtLeast(0)
|
||||
root?.let { activeRoot = it.path }
|
||||
activeCollection = collection
|
||||
c.setMediaItems(list, start, startMs)
|
||||
shuffled?.let { c.shuffleModeEnabled = it }
|
||||
c.prepare()
|
||||
c.play()
|
||||
}
|
||||
}
|
||||
|
||||
fun allow(paths: Collection<String>) {
|
||||
removed.removeAll(paths.toSet())
|
||||
}
|
||||
|
||||
fun toggle(context: Context, album: Soundtrack.Album, albumTitle: String, root: File?, collection: Int? = null) {
|
||||
run(context) { c ->
|
||||
if (root != null && root.path in removed) return@run
|
||||
val mine = if (collection != null) belongsCollection(collection) else belongs(root)
|
||||
if (mine && c.mediaItemCount > 0) {
|
||||
if (c.isPlaying) c.pause() else {
|
||||
if (c.playbackState == Player.STATE_ENDED) c.seekToDefaultPosition(0)
|
||||
c.play()
|
||||
}
|
||||
} else {
|
||||
val saved = if (collection != null) null else root?.let { r -> SoundtrackSettings.resume(context)?.takeIf { it.root == r.path && album.tracks.any { t -> t.id == it.id } } }
|
||||
play(context, album, albumTitle, saved?.id ?: album.tracks.firstOrNull()?.id, root = root, startMs = saved?.positionMs ?: 0L, collection = collection)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun pause(context: Context) {
|
||||
val live = controller
|
||||
if (live != null) live.pause() else if (future != null) pending += { it.pause() }
|
||||
}
|
||||
|
||||
fun next(context: Context) = run(context) { it.seekToNext() }
|
||||
fun previous(context: Context) = run(context) { c -> if (c.currentPosition > 3000L) c.seekTo(0) else c.seekToPrevious() }
|
||||
fun seekTo(context: Context, ms: Long) = run(context) { it.seekTo(ms) }
|
||||
fun setShuffle(context: Context, on: Boolean) = run(context) { it.shuffleModeEnabled = on }
|
||||
fun cycleRepeat(context: Context) = run(context) {
|
||||
it.repeatMode = when (it.repeatMode) {
|
||||
Player.REPEAT_MODE_OFF -> Player.REPEAT_MODE_ALL
|
||||
Player.REPEAT_MODE_ALL -> Player.REPEAT_MODE_ONE
|
||||
else -> Player.REPEAT_MODE_OFF
|
||||
}
|
||||
}
|
||||
fun setVolume(context: Context, volume: Float) = run(context) { it.volume = volume.coerceIn(0f, 1f) }
|
||||
|
||||
fun setSpeed(context: Context, value: Float) {
|
||||
SoundtrackSettings.load(context)
|
||||
SoundtrackSettings.setSpeed(context, value)
|
||||
run(context) { it.setPlaybackParameters(PlaybackParameters(SoundtrackSettings.speed, SoundtrackSettings.pitch)) }
|
||||
}
|
||||
|
||||
fun setPitch(context: Context, value: Float) {
|
||||
SoundtrackSettings.load(context)
|
||||
SoundtrackSettings.setPitch(context, value)
|
||||
run(context) { it.setPlaybackParameters(PlaybackParameters(SoundtrackSettings.speed, SoundtrackSettings.pitch)) }
|
||||
}
|
||||
|
||||
fun setSkipSilence(context: Context, on: Boolean) {
|
||||
SoundtrackSettings.load(context)
|
||||
SoundtrackSettings.setSkipSilence(context, on)
|
||||
run(context) { it.sendCustomCommand(SoundtrackService.SKIP_SILENCE, Bundle().apply { putBoolean(SoundtrackService.ARG_ON, on) }) }
|
||||
}
|
||||
|
||||
fun setEqualizer(context: Context, on: Boolean, bands: List<Int>, bass: Int) {
|
||||
SoundtrackSettings.load(context)
|
||||
SoundtrackSettings.setEqualizer(context, on, bands, bass)
|
||||
run(context) { sendEqualizer(it) }
|
||||
}
|
||||
|
||||
fun setIngame(context: Context, on: Boolean) {
|
||||
run(context) { it.sendCustomCommand(SoundtrackService.INGAME, Bundle().apply { putBoolean(SoundtrackService.ARG_ON, on) }) }
|
||||
}
|
||||
|
||||
fun setSleep(context: Context, minutes: Int) {
|
||||
sleepEndsAt = if (minutes > 0) System.currentTimeMillis() + minutes * 60_000L else 0L
|
||||
sleepTrackEnd = minutes < 0
|
||||
run(context) { it.sendCustomCommand(SoundtrackService.SLEEP, Bundle().apply { putInt(SoundtrackService.ARG_MINUTES, minutes) }) }
|
||||
}
|
||||
|
||||
fun sleepRemainingMs(): Long {
|
||||
val left = sleepEndsAt - System.currentTimeMillis()
|
||||
if (sleepEndsAt > 0L && left <= 0L) sleepEndsAt = 0L
|
||||
return left.coerceAtLeast(0L)
|
||||
}
|
||||
|
||||
fun stopIf(context: Context, root: File?) {
|
||||
root?.let { removed.add(it.path) }
|
||||
if (root == null || currentId?.startsWith(root.path + "/") != true) return
|
||||
run(context) { c ->
|
||||
c.stop()
|
||||
c.clearMediaItems()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
package com.droiddeck.launcher.playback
|
||||
|
||||
import android.app.PendingIntent
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.media.audiofx.BassBoost
|
||||
import android.media.audiofx.Equalizer
|
||||
import android.net.Uri
|
||||
import android.os.Bundle
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.Process
|
||||
import androidx.media3.common.AudioAttributes
|
||||
import androidx.media3.common.C
|
||||
import androidx.media3.common.MediaItem
|
||||
import androidx.media3.common.Player
|
||||
import androidx.media3.exoplayer.ExoPlayer
|
||||
import androidx.media3.session.CommandButton
|
||||
import androidx.media3.session.DefaultMediaNotificationProvider
|
||||
import androidx.media3.session.MediaSession
|
||||
import androidx.media3.session.MediaSessionService
|
||||
import androidx.media3.session.SessionCommand
|
||||
import androidx.media3.session.SessionResult
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.frontend.Soundtrack
|
||||
import com.google.common.collect.ImmutableList
|
||||
import com.google.common.util.concurrent.Futures
|
||||
import com.google.common.util.concurrent.ListenableFuture
|
||||
import java.io.File
|
||||
|
||||
private class EdgeButtonsProvider(context: Context) : DefaultMediaNotificationProvider(context) {
|
||||
override fun getMediaButtons(
|
||||
session: MediaSession, playerCommands: Player.Commands, customLayout: ImmutableList<CommandButton>, showPauseButton: Boolean,
|
||||
): ImmutableList<CommandButton> {
|
||||
val all = super.getMediaButtons(session, playerCommands, customLayout, showPauseButton)
|
||||
val custom = all.filter { it.sessionCommand != null }
|
||||
if (custom.size < 2) return all
|
||||
return ImmutableList.builder<CommandButton>()
|
||||
.add(custom.first())
|
||||
.addAll(all.filter { it.sessionCommand == null })
|
||||
.addAll(custom.drop(1))
|
||||
.build()
|
||||
}
|
||||
}
|
||||
|
||||
class SoundtrackService : MediaSessionService() {
|
||||
private var session: MediaSession? = null
|
||||
private var exo: ExoPlayer? = null
|
||||
private var equalizer: Equalizer? = null
|
||||
private var bassBoost: BassBoost? = null
|
||||
private var effectsSession = C.AUDIO_SESSION_ID_UNSET
|
||||
private var eqOn = false
|
||||
private var eqBands = IntArray(0)
|
||||
private var eqBass = 0
|
||||
private var sleepAtTrackEnd = false
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private val sleepRunnable = Runnable { session?.player?.pause() }
|
||||
private val covers = java.util.concurrent.Executors.newSingleThreadExecutor { r -> Thread(r, "soundtrack-cover").apply { isDaemon = true } }
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
val player = ExoPlayer.Builder(this)
|
||||
.setAudioAttributes(mediaAttributes(), !com.droiddeck.launcher.session.SessionPrefs.soundtracksIngame(this))
|
||||
.setHandleAudioBecomingNoisy(true)
|
||||
.setWakeMode(androidx.media3.common.C.WAKE_MODE_LOCAL)
|
||||
.build()
|
||||
exo = player
|
||||
val sessionIntent = packageManager.getLaunchIntentForPackage(packageName)?.let {
|
||||
PendingIntent.getActivity(this, 0, it, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
|
||||
}
|
||||
player.addListener(object : Player.Listener {
|
||||
override fun onShuffleModeEnabledChanged(shuffleModeEnabled: Boolean) = refreshButtons()
|
||||
override fun onRepeatModeChanged(repeatMode: Int) = refreshButtons()
|
||||
override fun onAudioSessionIdChanged(audioSessionId: Int) = applyEffects()
|
||||
override fun onPlayWhenReadyChanged(playWhenReady: Boolean, reason: Int) {
|
||||
if (!playWhenReady) sleepAtTrackEnd = false
|
||||
}
|
||||
override fun onMediaItemTransition(mediaItem: MediaItem?, reason: Int) {
|
||||
refreshTrackCover(mediaItem)
|
||||
val ended = reason == Player.MEDIA_ITEM_TRANSITION_REASON_AUTO || reason == Player.MEDIA_ITEM_TRANSITION_REASON_REPEAT
|
||||
if (sleepAtTrackEnd && ended) {
|
||||
sleepAtTrackEnd = false
|
||||
player.pause()
|
||||
}
|
||||
}
|
||||
})
|
||||
session = MediaSession.Builder(this, player).setCallback(Resolver()).apply { sessionIntent?.let { setSessionActivity(it) } }.build()
|
||||
setMediaNotificationProvider(EdgeButtonsProvider(this).apply { setSmallIcon(R.drawable.ic_soundtrack) })
|
||||
}
|
||||
|
||||
private fun mediaAttributes(): AudioAttributes =
|
||||
AudioAttributes.Builder().setUsage(C.USAGE_MEDIA).setContentType(C.AUDIO_CONTENT_TYPE_MUSIC).build()
|
||||
|
||||
private fun buttons(player: Player): ImmutableList<CommandButton> = ImmutableList.of(
|
||||
CommandButton.Builder()
|
||||
.setDisplayName(getString(R.string.soundtracks_shuffle))
|
||||
.setIconResId(if (player.shuffleModeEnabled) R.drawable.ic_shuffle_on else R.drawable.ic_shuffle_off)
|
||||
.setSessionCommand(SHUFFLE)
|
||||
.build(),
|
||||
CommandButton.Builder()
|
||||
.setDisplayName(
|
||||
getString(
|
||||
when (player.repeatMode) {
|
||||
Player.REPEAT_MODE_ALL -> R.string.soundtracks_repeat_all
|
||||
Player.REPEAT_MODE_ONE -> R.string.soundtracks_repeat_one
|
||||
else -> R.string.soundtracks_repeat_off
|
||||
},
|
||||
),
|
||||
)
|
||||
.setIconResId(
|
||||
when (player.repeatMode) {
|
||||
Player.REPEAT_MODE_ALL -> R.drawable.ic_repeat_all
|
||||
Player.REPEAT_MODE_ONE -> R.drawable.ic_repeat_one
|
||||
else -> R.drawable.ic_repeat_off
|
||||
},
|
||||
)
|
||||
.setSessionCommand(REPEAT)
|
||||
.build(),
|
||||
)
|
||||
|
||||
private fun hasPinnedArt(item: MediaItem): Boolean =
|
||||
item.mediaMetadata.artworkUri?.path.orEmpty().let { it.contains("/steam-art/") || it.contains("/soundtrack-art/") }
|
||||
|
||||
private fun refreshTrackCover(item: MediaItem?) {
|
||||
val current = item ?: return
|
||||
if (hasPinnedArt(current)) return
|
||||
val file = File(current.mediaId)
|
||||
covers.execute {
|
||||
val art = Soundtrack.trackCover(this, file) ?: return@execute
|
||||
handler.post {
|
||||
val player = exo ?: return@post
|
||||
val live = player.currentMediaItem ?: return@post
|
||||
val uri = Uri.fromFile(art)
|
||||
if (live.mediaId != current.mediaId || live.mediaMetadata.artworkUri == uri || hasPinnedArt(live)) return@post
|
||||
player.replaceMediaItem(
|
||||
player.currentMediaItemIndex,
|
||||
live.buildUpon().setMediaMetadata(live.mediaMetadata.buildUpon().setArtworkUri(uri).build()).build(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun releaseEffects() {
|
||||
runCatching { equalizer?.release() }
|
||||
runCatching { bassBoost?.release() }
|
||||
equalizer = null
|
||||
bassBoost = null
|
||||
effectsSession = C.AUDIO_SESSION_ID_UNSET
|
||||
}
|
||||
|
||||
private fun applyEffects() {
|
||||
val id = exo?.audioSessionId ?: C.AUDIO_SESSION_ID_UNSET
|
||||
if (!eqOn || id == C.AUDIO_SESSION_ID_UNSET) {
|
||||
releaseEffects()
|
||||
return
|
||||
}
|
||||
if (id != effectsSession) {
|
||||
releaseEffects()
|
||||
effectsSession = id
|
||||
equalizer = runCatching { Equalizer(0, id) }.getOrNull()
|
||||
bassBoost = runCatching { BassBoost(0, id) }.getOrNull()
|
||||
}
|
||||
runCatching {
|
||||
equalizer?.let { eq ->
|
||||
val range = eq.bandLevelRange
|
||||
for (band in 0 until minOf(eq.numberOfBands.toInt(), eqBands.size)) {
|
||||
eq.setBandLevel(band.toShort(), eqBands[band].coerceIn(range[0].toInt(), range[1].toInt()).toShort())
|
||||
}
|
||||
eq.enabled = true
|
||||
}
|
||||
}
|
||||
runCatching {
|
||||
bassBoost?.let { boost ->
|
||||
if (boost.strengthSupported) boost.setStrength(eqBass.coerceIn(0, 1000).toShort())
|
||||
boost.enabled = eqBass > 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun setSleep(minutes: Int) {
|
||||
handler.removeCallbacks(sleepRunnable)
|
||||
sleepAtTrackEnd = false
|
||||
if (minutes > 0) handler.postDelayed(sleepRunnable, minutes * 60_000L)
|
||||
else if (minutes < 0) sleepAtTrackEnd = true
|
||||
}
|
||||
|
||||
private fun refreshButtons() {
|
||||
val live = session ?: return
|
||||
live.setCustomLayout(buttons(live.player))
|
||||
}
|
||||
|
||||
override fun onGetSession(controllerInfo: MediaSession.ControllerInfo): MediaSession? = session
|
||||
|
||||
override fun onTaskRemoved(rootIntent: Intent?) {
|
||||
val player = session?.player
|
||||
if (player == null || !player.playWhenReady || player.mediaItemCount == 0 || player.playbackState == Player.STATE_ENDED) stopSelf()
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
handler.removeCallbacks(sleepRunnable)
|
||||
covers.shutdownNow()
|
||||
releaseEffects()
|
||||
session?.let {
|
||||
it.player.release()
|
||||
it.release()
|
||||
}
|
||||
session = null
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val HINT_OWNER = "droiddeck.owner"
|
||||
private val SHUFFLE = SessionCommand("droiddeck.shuffle", Bundle.EMPTY)
|
||||
private val REPEAT = SessionCommand("droiddeck.repeat", Bundle.EMPTY)
|
||||
val SKIP_SILENCE = SessionCommand("droiddeck.skipsilence", Bundle.EMPTY)
|
||||
val EQUALIZER = SessionCommand("droiddeck.equalizer", Bundle.EMPTY)
|
||||
val SLEEP = SessionCommand("droiddeck.sleep", Bundle.EMPTY)
|
||||
val INGAME = SessionCommand("droiddeck.ingame", Bundle.EMPTY)
|
||||
const val ARG_ON = "on"
|
||||
const val ARG_BANDS = "bands"
|
||||
const val ARG_BASS = "bass"
|
||||
const val ARG_MINUTES = "minutes"
|
||||
}
|
||||
|
||||
private inner class Resolver : MediaSession.Callback {
|
||||
private fun isOwner(controller: MediaSession.ControllerInfo) =
|
||||
controller.uid == Process.myUid() && controller.connectionHints.getBoolean(HINT_OWNER, false)
|
||||
|
||||
override fun onConnect(session: MediaSession, controller: MediaSession.ControllerInfo): MediaSession.ConnectionResult =
|
||||
if (controller.uid == Process.myUid() || controller.isTrusted) {
|
||||
MediaSession.ConnectionResult.AcceptedResultBuilder(session)
|
||||
.setAvailableSessionCommands(
|
||||
MediaSession.ConnectionResult.DEFAULT_SESSION_COMMANDS.buildUpon().add(SHUFFLE).add(REPEAT).add(SKIP_SILENCE).add(EQUALIZER).add(SLEEP).add(INGAME).build(),
|
||||
)
|
||||
.setCustomLayout(buttons(session.player))
|
||||
.build()
|
||||
} else {
|
||||
MediaSession.ConnectionResult.reject()
|
||||
}
|
||||
|
||||
override fun onCustomCommand(
|
||||
session: MediaSession, controller: MediaSession.ControllerInfo, customCommand: SessionCommand, args: Bundle,
|
||||
): ListenableFuture<SessionResult> {
|
||||
val player = session.player
|
||||
when (customCommand.customAction) {
|
||||
SHUFFLE.customAction -> player.shuffleModeEnabled = !player.shuffleModeEnabled
|
||||
REPEAT.customAction -> player.repeatMode = when (player.repeatMode) {
|
||||
Player.REPEAT_MODE_OFF -> Player.REPEAT_MODE_ALL
|
||||
Player.REPEAT_MODE_ALL -> Player.REPEAT_MODE_ONE
|
||||
else -> Player.REPEAT_MODE_OFF
|
||||
}
|
||||
SKIP_SILENCE.customAction, EQUALIZER.customAction, SLEEP.customAction, INGAME.customAction -> {
|
||||
if (!isOwner(controller)) return Futures.immediateFuture(SessionResult(SessionResult.RESULT_ERROR_PERMISSION_DENIED))
|
||||
when (customCommand.customAction) {
|
||||
SKIP_SILENCE.customAction -> exo?.skipSilenceEnabled = args.getBoolean(ARG_ON)
|
||||
INGAME.customAction -> exo?.setAudioAttributes(mediaAttributes(), !args.getBoolean(ARG_ON))
|
||||
EQUALIZER.customAction -> {
|
||||
eqOn = args.getBoolean(ARG_ON)
|
||||
eqBands = args.getIntArray(ARG_BANDS) ?: IntArray(0)
|
||||
eqBass = args.getInt(ARG_BASS)
|
||||
applyEffects()
|
||||
}
|
||||
else -> setSleep(args.getInt(ARG_MINUTES))
|
||||
}
|
||||
}
|
||||
else -> return Futures.immediateFuture(SessionResult(SessionResult.RESULT_ERROR_NOT_SUPPORTED))
|
||||
}
|
||||
return Futures.immediateFuture(SessionResult(SessionResult.RESULT_SUCCESS))
|
||||
}
|
||||
|
||||
override fun onAddMediaItems(
|
||||
mediaSession: MediaSession, controller: MediaSession.ControllerInfo, mediaItems: MutableList<MediaItem>,
|
||||
): ListenableFuture<MutableList<MediaItem>> {
|
||||
if (!isOwner(controller)) return Futures.immediateFailedFuture(SecurityException("Only DroidDeck can queue soundtrack files"))
|
||||
val resolved = mediaItems.mapNotNull { item ->
|
||||
val file = File(item.mediaId)
|
||||
if (Soundtrack.isAudio(file)) item.buildUpon().setUri(Uri.fromFile(file)).build() else null
|
||||
}.toMutableList()
|
||||
return Futures.immediateFuture(resolved)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package com.droiddeck.launcher.playback
|
||||
|
||||
import android.content.Context
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableFloatStateOf
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
|
||||
object SoundtrackSettings {
|
||||
const val MIN_RATE = 0.5f
|
||||
const val MAX_RATE = 2f
|
||||
|
||||
var speed by mutableFloatStateOf(1f)
|
||||
private set
|
||||
var pitch by mutableFloatStateOf(1f)
|
||||
private set
|
||||
var skipSilence by mutableStateOf(false)
|
||||
private set
|
||||
var eqOn by mutableStateOf(false)
|
||||
private set
|
||||
var bands by mutableStateOf<List<Int>>(emptyList())
|
||||
private set
|
||||
var bass by mutableIntStateOf(0)
|
||||
private set
|
||||
|
||||
class Resume(val root: String, val id: String, val positionMs: Long)
|
||||
|
||||
private var loaded = false
|
||||
|
||||
private fun prefs(context: Context) = context.applicationContext.getSharedPreferences("soundtrack_settings", Context.MODE_PRIVATE)
|
||||
|
||||
@Synchronized
|
||||
fun load(context: Context) {
|
||||
if (loaded) return
|
||||
loaded = true
|
||||
val p = prefs(context)
|
||||
speed = p.getFloat("speed", 1f).coerceIn(MIN_RATE, MAX_RATE)
|
||||
pitch = p.getFloat("pitch", 1f).coerceIn(MIN_RATE, MAX_RATE)
|
||||
skipSilence = p.getBoolean("skipSilence", false)
|
||||
eqOn = p.getBoolean("eqOn", false)
|
||||
bands = p.getString("bands", "").orEmpty().split(',').mapNotNull { it.trim().toIntOrNull() }
|
||||
bass = p.getInt("bass", 0).coerceIn(0, 1000)
|
||||
}
|
||||
|
||||
fun setSpeed(context: Context, value: Float) {
|
||||
speed = value.coerceIn(MIN_RATE, MAX_RATE)
|
||||
prefs(context).edit().putFloat("speed", speed).apply()
|
||||
}
|
||||
|
||||
fun setPitch(context: Context, value: Float) {
|
||||
pitch = value.coerceIn(MIN_RATE, MAX_RATE)
|
||||
prefs(context).edit().putFloat("pitch", pitch).apply()
|
||||
}
|
||||
|
||||
fun setSkipSilence(context: Context, on: Boolean) {
|
||||
skipSilence = on
|
||||
prefs(context).edit().putBoolean("skipSilence", on).apply()
|
||||
}
|
||||
|
||||
fun setEqualizer(context: Context, on: Boolean, levels: List<Int>, bassStrength: Int) {
|
||||
eqOn = on
|
||||
bands = levels
|
||||
bass = bassStrength.coerceIn(0, 1000)
|
||||
prefs(context).edit().putBoolean("eqOn", on).putString("bands", levels.joinToString(",")).putInt("bass", bass).apply()
|
||||
}
|
||||
|
||||
fun resume(context: Context): Resume? {
|
||||
val p = prefs(context)
|
||||
val root = p.getString("resumeRoot", null) ?: return null
|
||||
val id = p.getString("resumeId", null) ?: return null
|
||||
return Resume(root, id, p.getLong("resumePosition", 0L))
|
||||
}
|
||||
|
||||
fun saveResume(context: Context, root: String, id: String, positionMs: Long) {
|
||||
prefs(context).edit().putString("resumeRoot", root).putString("resumeId", id).putLong("resumePosition", positionMs.coerceAtLeast(0L)).apply()
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user