Native Android client for Spotify, built with Jetpack Compose
Kotlin ad-freeadblockandroidjetpack-composekotlinlyricsmusic-playermusic-videomyspotispotifyspotify-adblockerspotify-clientspotify-connectspotui
Player settings: the Immersive player's volume bar can be hidden and its cover swiped sideways to change song (#127), the Classic podcast player closes when pulled down, the lyrics keep the screen on (a switch, on by default) and "More lyrics sources" is in Settings too, in both looks, and spatial audio widens the stereo by mid/side with a width slider on the equalizer page, for extension, downloaded and local songs only, bit for bit untouched when off (#95)
kota-zob051a3a0b96c
diff --git a/base/app/src/main/java/com/music/spotui/data/preferences/EqualizerPref.kt b/base/app/src/main/java/com/music/spotui/data/preferences/EqualizerPref.ktindex f54113ca..8848a4a8 100644--- a/base/app/src/main/java/com/music/spotui/data/preferences/EqualizerPref.kt+++ b/base/app/src/main/java/com/music/spotui/data/preferences/EqualizerPref.kt@@ -7,6 +7,7 @@ import androidx.compose.runtime.setValueimport com.music.spotui.di.EqBandsimport com.music.spotui.di.EqTuningimport com.music.spotui.di.Equalizer+import com.music.spotui.di.Spatial/** The equalizer's ready-made curves: ten band gains and the preamp that keeps them under full scale, in dB. */enum class EqPreset(val gains: FloatArray, val preamp: Float) {@@ -36,6 +37,9 @@ enum class EqPreset(val gains: FloatArray, val preamp: Float) {* Speed: 0.5× to 2× for everything the local player plays, 1× by default (podcasts streamed by* Spotify keep their own speed, the podcast player's). Off 1×, Spotify does not follow the song* (see ConnectMirror): its page plays at 1× only.+ *+ * Spatial audio: the stereo widened by mid/side processing (see SpatialProcessor), off by default,+ * on its own switch (the equalizer may be off).*/object EqualizerPref {private const val PREF = "equalizer_prefs"@@ -54,6 +58,10 @@ object EqualizerPref {private setvar skipSilence by mutableStateOf(p.getBoolean("skip_silence", false))private set+ var spatial by mutableStateOf(p.getBoolean("spatial", false))+ private set+ var spatialWidth by mutableStateOf(p.getFloat("spatial_width", Spatial.DEFAULT_WIDTH).coerceIn(Spatial.MIN_WIDTH, Spatial.MAX_WIDTH))+ private set/** The gains shown and heard: the preset's, or the user's own. */val gains: FloatArray get() = if (preset == EqPreset.CUSTOM) customGains else preset.gains@@ -115,8 +123,22 @@ object EqualizerPref {com.music.spotui.di.LocalPlayer.applyPlayback()}- /** Hands the curve to the players' equalizers (read on their audio threads). */+ fun setSpatial(c: Context, on: Boolean) {+ spatial = on+ prefs(c).edit().putBoolean("spatial", on).apply()+ push()+ }++ /** Heard at once, gliding; kept when [save] (a slider saves once, at the end of its drag). */+ fun setSpatialWidth(c: Context, value: Float, save: Boolean = true) {+ spatialWidth = value.coerceIn(Spatial.MIN_WIDTH, Spatial.MAX_WIDTH)+ push()+ if (save) prefs(c).edit().putFloat("spatial_width", spatialWidth).apply()+ }++ /** Hands the curve and the width to the players' audio stages (read on their audio threads). */private fun push() {Equalizer.current = if (enabled) EqTuning(gains, preamp) else null+ Spatial.current = if (spatial) spatialWidth else null}}diff --git a/base/app/src/main/java/com/music/spotui/data/preferences/SettingsPref.kt b/base/app/src/main/java/com/music/spotui/data/preferences/SettingsPref.ktindex bc8e5eb0..5c346b2e 100644--- a/base/app/src/main/java/com/music/spotui/data/preferences/SettingsPref.kt+++ b/base/app/src/main/java/com/music/spotui/data/preferences/SettingsPref.kt@@ -305,3 +305,34 @@ object PlayerModesPref {prefs(c).edit().putBoolean(KEY, value).apply()}}++/**+ * "Volume bar in the player" (Settings > Display, Immersive look): the volume slider under the+ * transport. On by default; off, the phone's volume keys still do it, and the controls sit lower.+ */+object PlayerVolumePref {+ private const val KEY = "immersive_player_volume"+ var on by androidx.compose.runtime.mutableStateOf(prefs(com.music.spotui.di.Graph.app).getBoolean(KEY, true))+ private set++ fun set(c: Context, value: Boolean) {+ on = value+ prefs(c).edit().putBoolean(KEY, value).apply()+ }+}++/**+ * "Keep the screen on with lyrics" (Settings > Playback, both looks): while the lyrics are open+ * the screen does not go dark, so the lines can be followed. On by default. Read as state by the+ * lyrics of both looks.+ */+object LyricsKeepAwakePref {+ private const val KEY = "lyrics_keep_screen_on"+ var on by androidx.compose.runtime.mutableStateOf(prefs(com.music.spotui.di.Graph.app).getBoolean(KEY, true))+ private set++ fun set(c: Context, value: Boolean) {+ on = value+ prefs(c).edit().putBoolean(KEY, value).apply()+ }+}diff --git a/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt b/base/app/src/main/java/com/music/spotui/di/LocalPlayer.ktindex fe85966b..bfa4d843 100644--- a/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt+++ b/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt@@ -74,8 +74,10 @@ object LocalPlayer {.also(::tune)/**- * The default renderers, with the equalizer in the audio chain (each player its own, see- * EqualizerProcessor), ahead of the silence skipping and the speed the sink adds after it.+ * The default renderers, with the equalizer and the spatial stage after it in the audio chain+ * (each player its own, see EqualizerProcessor and SpatialProcessor), ahead of the silence+ * skipping and the speed the sink adds after them. The spatial stage is last of the two: its+ * limiter is what keeps a widened peak under full scale.*/@androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)private object Renderers : androidx.media3.exoplayer.DefaultRenderersFactory(Graph.app) {@@ -83,7 +85,7 @@ object LocalPlayer {androidx.media3.exoplayer.audio.DefaultAudioSink.Builder(context).setEnableFloatOutput(enableFloatOutput).setEnableAudioTrackPlaybackParams(enableAudioTrackPlaybackParams)- .setAudioProcessors(arrayOf(EqualizerProcessor()))+ .setAudioProcessors(arrayOf(EqualizerProcessor(), SpatialProcessor())).build()}diff --git a/base/app/src/main/java/com/music/spotui/di/SpatialProcessor.kt b/base/app/src/main/java/com/music/spotui/di/SpatialProcessor.ktnew file mode 100644index 00000000..94629457--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/di/SpatialProcessor.kt@@ -0,0 +1,133 @@+package com.music.spotui.di++import androidx.media3.common.C+import androidx.media3.common.audio.AudioProcessor+import androidx.media3.common.audio.BaseAudioProcessor+import androidx.media3.common.util.UnstableApi+import java.nio.ByteBuffer+import java.nio.ByteOrder+import kotlin.math.abs+import kotlin.math.exp+import kotlin.math.max+import kotlin.math.min+import kotlin.math.roundToInt++/** The stereo width the local player's spatial stage follows; null: off (see EqualizerPref). Read on the audio thread. */+object Spatial {+ /** 1 is the song as it came; above, the sides are brought out. */+ const val MIN_WIDTH = 1.1f+ const val MAX_WIDTH = 2.5f+ const val DEFAULT_WIDTH = 1.6f+ @Volatile var current: Float? = null+}++/**+ * Spatial audio for the local player (extensions' streams, downloads, the phone's files): the+ * stereo image widened by mid/side processing, after the equalizer in ExoPlayer's chain. Each+ * player has its own (the fading-out copy of a crossfade too), all following [source].+ *+ * The mid (L+R)/2 stays as it is, the side (L-R)/2 is raised by the width, and the whole is turned+ * down a little so a wider song does not sound louder. A peak the wider image would push past+ * full scale is caught by a limiter at -0.1 dBFS rather than clipped. Off, or once a change back to+ * width 1 has glided there, it copies its input as it came, bit for bit. Stereo 16-bit and float+ * PCM only: mono and multichannel pass untouched (the processor is then inactive).+ */+@UnstableApi+class SpatialProcessor(private val source: () -> Float? = { Spatial.current }) : BaseAudioProcessor() {+ private var float = false+ private var width = 1f+ private var limiterGain = 1f+ private var release = 0f++ override fun onConfigure(inputAudioFormat: AudioProcessor.AudioFormat): AudioProcessor.AudioFormat {+ val enc = inputAudioFormat.encoding+ if ((enc != C.ENCODING_PCM_16BIT && enc != C.ENCODING_PCM_FLOAT) || inputAudioFormat.channelCount != 2 || inputAudioFormat.sampleRate <= 0)+ return AudioProcessor.AudioFormat.NOT_SET+ float = enc == C.ENCODING_PCM_FLOAT+ // Back up in about 200 ms once a peak has passed.+ release = 1f - exp(-1f / (0.2f * inputAudioFormat.sampleRate))+ return inputAudioFormat+ }++ override fun onFlush() {+ // A new stream (or a seek) starts at the width, not gliding to it.+ width = target()+ limiterGain = 1f+ }++ override fun onReset() {+ width = 1f; limiterGain = 1f+ }++ private fun target(): Float = source()?.coerceIn(1f, Spatial.MAX_WIDTH) ?: 1f++ override fun queueInput(inputBuffer: ByteBuffer) {+ if (!inputBuffer.hasRemaining()) return+ val target = target()+ if (target == 1f && abs(width - 1f) < SETTLED && limiterGain > 1f - SETTLED) {+ // The exact copy: nothing heard is changed, nothing computed.+ width = 1f; limiterGain = 1f+ val out = replaceOutputBuffer(inputBuffer.remaining())+ out.put(inputBuffer)+ out.flip()+ return+ }+ val frameBytes = if (float) 8 else 4+ val frames = inputBuffer.remaining() / frameBytes+ if (frames == 0) return+ val out = replaceOutputBuffer(frames * frameBytes)+ inputBuffer.order(ByteOrder.nativeOrder())+ var left = frames+ while (left > 0) {+ val block = min(left, GLIDE_FRAMES)+ width += (target - width) * GLIDE_RATE+ if (abs(target - width) < SETTLED) width = target+ // Back at width 1, nothing can go past full scale any more: the limiter lets go as fast+ // as a width glides, and the copy takes over once it has.+ val unwinding = width == 1f+ if (unwinding) limiterGain += (1f - limiterGain) * GLIDE_RATE+ val gain = makeup(width)+ repeat(block) {+ val l = if (float) inputBuffer.float else inputBuffer.short * (1f / 32768f)+ val r = if (float) inputBuffer.float else inputBuffer.short * (1f / 32768f)+ val mid = (l + r) * 0.5f+ val side = (l - r) * 0.5f * width+ var outL = (mid + side) * gain+ var outR = (mid - side) * gain+ // The limiter: down at once to what keeps this frame under the ceiling, back up slowly.+ if (!unwinding) {+ val peak = max(abs(outL), abs(outR))+ limiterGain += (1f - limiterGain) * release+ if (peak * limiterGain > CEILING) limiterGain = CEILING / peak+ }+ outL *= limiterGain+ outR *= limiterGain+ if (float) {+ out.putFloat(outL); out.putFloat(outR)+ } else {+ out.putShort((outL * 32768f).roundToInt().coerceIn(-32768, 32767).toShort())+ out.putShort((outR * 32768f).roundToInt().coerceIn(-32768, 32767).toShort())+ }+ }+ left -= block+ }+ out.flip()+ }++ companion object {+ /**+ * The level the whole is turned down to at [width]: a quarter of what the side gained, so a+ * centred voice stays close to where it was (0.8, -1.9 dB, at width 2) and the limiter is+ * left the rare peaks of a hard-panned sound.+ */+ internal fun makeup(width: Float): Float = 1f / (1f + (width - 1f) * 0.25f)++ /** Frames between two steps of a glide (about 1.5 ms at 44.1 kHz). */+ private const val GLIDE_FRAMES = 64+ /** The part of what is left of a change made at each step (about 18 ms to get most of the way). */+ private const val GLIDE_RATE = 0.08f+ private const val SETTLED = 0.001f+ /** -0.1 dBFS. */+ private const val CEILING = 0.9886f+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/components/PullToDismiss.kt b/base/app/src/main/java/com/music/spotui/ui/components/PullToDismiss.ktindex baf56df2..4774719a 100644--- a/base/app/src/main/java/com/music/spotui/ui/components/PullToDismiss.kt+++ b/base/app/src/main/java/com/music/spotui/ui/components/PullToDismiss.kt@@ -1,13 +1,22 @@package com.music.spotui.ui.componentsimport androidx.compose.animation.core.Animatable+import androidx.compose.foundation.gestures.awaitEachGesture+import androidx.compose.foundation.gestures.awaitFirstDown+import androidx.compose.foundation.gestures.awaitVerticalTouchSlopOrCancellation+import androidx.compose.foundation.gestures.verticalDragimport androidx.compose.runtime.Composableimport androidx.compose.runtime.rememberimport androidx.compose.runtime.rememberCoroutineScopeimport androidx.compose.runtime.rememberUpdatedState+import androidx.compose.ui.Modifierimport androidx.compose.ui.geometry.Offsetimport androidx.compose.ui.input.nestedscroll.NestedScrollConnectionimport androidx.compose.ui.input.nestedscroll.NestedScrollSource+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.input.pointer.positionChange+import androidx.compose.ui.input.pointer.util.VelocityTracker+import androidx.compose.ui.input.pointer.util.addPointerInputChangeimport androidx.compose.ui.platform.LocalDensityimport androidx.compose.ui.unit.Velocityimport androidx.compose.ui.unit.dp@@ -18,7 +27,8 @@ import kotlinx.coroutines.launch* A full-screen sheet pulled down from the top of its list closes, like the official* player: the sheet follows the finger (with some resistance) and closes past* [thresholdPx] or on a quick flick down; otherwise it springs back. Attach- * [connection] to the list's `nestedScroll` and move the sheet by [offset].+ * [connection] to the list's `nestedScroll` (or, on a screen with no list, [pullToDismiss] to the+ * screen) and move the sheet by [offset].*/class PullToDismissState internal constructor(private val scope: CoroutineScope,@@ -38,35 +48,55 @@ class PullToDismissState internal constructor(scope.launch { pull.snapTo(raw * RESISTANCE) }}+ /**+ * The finger moved [delta] pixels (down is positive): down pulls the sheet, back up undoes the+ * pull first. Returns what was taken of it.+ */+ fun drag(delta: Float): Float {+ val used = when {+ delta < 0f -> maxOf(delta, -raw)+ enabled && !dismissed -> delta+ else -> 0f+ }+ if (used == 0f) return 0f+ raw += used+ follow()+ return used+ }++ /** The finger lifted at [velocity] pixels a second (down is positive): closes, or springs back. */+ fun release(velocity: Float) {+ scope.launch { settle(velocity) }+ }++ /** False when the sheet was not pulled (nothing to settle). */+ private suspend fun settle(velocity: Float): Boolean {+ if (raw <= 0f) return false+ if (raw > thresholdPx || velocity > flingPx) {+ dismissed = true+ dismiss()+ } else {+ raw = 0f+ pull.animateTo(0f)+ }+ return true+ }+val connection = object : NestedScrollConnection {// Pushing back up first undoes the pull, before the list scrolls.override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {if (raw <= 0f || available.y >= 0f || source != NestedScrollSource.UserInput) return Offset.Zero- val used = maxOf(available.y, -raw)- raw += used- follow()- return Offset(0f, used)+ return Offset(0f, drag(available.y))}// What the list could not scroll (it is at its top) pulls the sheet down.override fun onPostScroll(consumed: Offset, available: Offset, source: NestedScrollSource): Offset {- if (!enabled || dismissed || available.y <= 0f || source != NestedScrollSource.UserInput) return Offset.Zero- raw += available.y- follow()- return Offset(0f, available.y)+ if (available.y <= 0f || source != NestedScrollSource.UserInput) return Offset.Zero+ return Offset(0f, drag(available.y))}- override suspend fun onPreFling(available: Velocity): Velocity {- if (raw <= 0f) return Velocity.Zero- if (raw > thresholdPx || available.y > flingPx) {- dismissed = true- dismiss()- } else {- raw = 0f- pull.animateTo(0f)- }- return available- }+ override suspend fun onPreFling(available: Velocity): Velocity =+ if (settle(available.y)) available else Velocity.Zero}private companion object {@@ -74,6 +104,36 @@ class PullToDismissState internal constructor(}}+/**+ * A drag down anywhere on a screen with no list to scroll (the podcast player) pulls the sheet,+ * as a list's overscroll does through [PullToDismissState.connection]. Upward is not ours: nothing+ * is consumed until the finger has gone down past the touch slop, so taps, the progress bar and a+ * child's own gesture keep working. Put it ahead of the graphicsLayer that moves the sheet by+ * [PullToDismissState.offset]: the finger is then measured on the screen, not on the moving sheet.+ */+fun Modifier.pullToDismiss(state: PullToDismissState): Modifier = pointerInput(state) {+ awaitEachGesture {+ val down = awaitFirstDown(requireUnconsumed = false)+ var pulled = 0f+ val drag = awaitVerticalTouchSlopOrCancellation(down.id) { change, overSlop ->+ if (overSlop > 0f) {+ pulled = overSlop+ change.consume()+ }+ }+ if (drag == null || pulled <= 0f) return@awaitEachGesture+ val velocity = VelocityTracker()+ velocity.addPointerInputChange(drag)+ state.drag(pulled)+ val finished = verticalDrag(drag.id) { change ->+ velocity.addPointerInputChange(change)+ state.drag(change.positionChange().y)+ change.consume()+ }+ state.release(if (finished) velocity.calculateVelocity().y else 0f)+ }+}+@Composablefun rememberPullToDismiss(onDismiss: () -> Unit): PullToDismissState {val scope = rememberCoroutineScope()diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveEqualizerScreen.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveEqualizerScreen.ktindex b57ca679..9fb02162 100644--- a/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveEqualizerScreen.kt+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveEqualizerScreen.kt@@ -24,12 +24,15 @@ import app.myspoti.engine.Rimport com.music.spotui.data.preferences.EqPresetimport com.music.spotui.data.preferences.EqualizerPrefimport com.music.spotui.di.EqBands+import com.music.spotui.di.Spatialimport com.music.spotui.ui.immersive.Immersiveimport com.music.spotui.ui.look.ThinSliderimport com.music.spotui.ui.screens.dbTextimport com.music.spotui.ui.screens.eqBandLabelimport com.music.spotui.ui.screens.eqPresetLabelimport com.music.spotui.ui.screens.speedText+import com.music.spotui.ui.screens.widthStep+import com.music.spotui.ui.screens.widthText/*** Settings > Playback > Equalizer (Immersive): the Classic page's settings (see EqualizerScreen)@@ -78,6 +81,26 @@ fun ImmersiveEqualizerScreen(navController: NavController) {onClick = { pref.setPreset(ctx, EqPreset.FLAT) })}}+ immersiveGroup("spatial", headerRes = R.string.spatial_title, footerRes = R.string.spatial_detail) {+ row { ImmersiveSwitchRow(stringResource(R.string.spatial_enable), checked = pref.spatial, onChecked = { pref.setSpatial(ctx, it) }) }+ row {+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp).padding(horizontal = 16.dp)) {+ Text(stringResource(R.string.spatial_width), style = Immersive.Body.copy(color = if (pref.spatial) Immersive.Text else Immersive.TextTertiary),+ modifier = Modifier.width(64.dp))+ val min = Spatial.MIN_WIDTH+ val max = Spatial.MAX_WIDTH+ ThinSlider(+ value = (pref.spatialWidth - min) / (max - min),+ onValueChange = { if (pref.spatial) pref.setSpatialWidth(ctx, widthStep(min + it * (max - min)), save = false) },+ onValueChangeFinished = { pref.setSpatialWidth(ctx, pref.spatialWidth) },+ modifier = Modifier.weight(1f),+ activeColor = if (pref.spatial) Immersive.Accent else Immersive.TextTertiary,+ )+ Spacer(Modifier.width(10.dp))+ Text(widthText(pref.spatialWidth), style = Immersive.Caption, modifier = Modifier.width(56.dp), textAlign = TextAlign.End)+ }+ }+ }immersiveGroup("speed", headerRes = R.string.equalizer_speed, footerRes = R.string.equalizer_speed_detail) {row {ImmersiveSegmentedControl(diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveSettingsScreen.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveSettingsScreen.ktindex a864bae2..be993f79 100644--- a/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveSettingsScreen.kt+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveSettingsScreen.kt@@ -207,6 +207,7 @@ private fun PlaybackPage(navController: NavController, open: (SettingsPage) -> Uvar headsetSkip by remember { mutableStateOf(app.myspoti.host.android.PlaybackService.skipsOnEpisodes(ctx)) }var keepPlaying by remember { mutableStateOf(app.myspoti.host.android.PlaybackService.keepsPlayingOnClose(ctx)) }var wordSync by remember { mutableStateOf(com.music.spotui.data.preferences.isLyricsWordSync(ctx)) }+ var lyricsExtra by remember { mutableStateOf(com.music.spotui.data.preferences.isLyricsExtraSources(ctx)) }val crossfade = com.music.spotui.data.preferences.CrossfadePref.seconds// The first source of the audio order, when it is an extension announcing settings here:// they show, and Spotify's quality (kept, still used for what Spotify plays) leaves the screen.@@ -317,6 +318,27 @@ private fun PlaybackPage(navController: NavController, open: (SettingsPage) -> Udetail = stringResource(if (wordSync) R.string.lyrics_word_sync_on else R.string.lyrics_word_sync_off),)}+ // NetEase and Genius after Spotify and LRCLIB (also in the lyrics' own menu).+ row {+ ImmersiveSwitchRow(+ stringResource(R.string.lyrics_extra_title), checked = lyricsExtra,+ onChecked = {+ lyricsExtra = it+ com.music.spotui.data.preferences.setLyricsExtraSources(ctx, it)+ com.music.spotui.data.api.LyricsApi.extraSources = it+ com.music.spotui.data.api.LyricsApi.forgetAll()+ },+ detail = stringResource(R.string.lyrics_extra_summary),+ )+ }+ row {+ ImmersiveSwitchRow(+ stringResource(R.string.settings_lyrics_keep_awake_title),+ checked = com.music.spotui.data.preferences.LyricsKeepAwakePref.on,+ onChecked = { com.music.spotui.data.preferences.LyricsKeepAwakePref.set(ctx, it) },+ detail = stringResource(R.string.settings_lyrics_keep_awake_detail),+ )+ }}}}@@ -547,6 +569,10 @@ private fun DisplayPage(open: (SettingsPage) -> Unit, back: () -> Unit) {ImmersiveSwitchRow(stringResource(R.string.settings_player_modes_title), checked = com.music.spotui.data.preferences.PlayerModesPref.on,onChecked = { com.music.spotui.data.preferences.PlayerModesPref.set(ctx, it) }, detail = stringResource(R.string.settings_player_modes_detail))}+ row {+ ImmersiveSwitchRow(stringResource(R.string.settings_player_volume_title), checked = com.music.spotui.data.preferences.PlayerVolumePref.on,+ onChecked = { com.music.spotui.data.preferences.PlayerVolumePref.set(ctx, it) }, detail = stringResource(R.string.settings_player_volume_detail))+ }}}immersiveGroup("layout") {diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/player/ImmersivePlayer.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/player/ImmersivePlayer.ktindex 13188228..a790928e 100644--- a/base/app/src/main/java/com/music/spotui/ui/immersive/player/ImmersivePlayer.kt+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/player/ImmersivePlayer.kt@@ -6,9 +6,10 @@* Changes: only the portrait layout is taken: the artwork with its step back on pause, the move* of the artwork to a small header (title beside it) when the lyrics or the queue open, the* title row with its round glyphs, the scrubber, transport, volume and bottom rows, and the- * sheet's drag to close. The full-bleed banner, Canvas clips, track-swipe on the cover, version- * switching, the lyric strip and the dock are left out. The landscape layout (cover beside the- * controls) and the Canvas behind the player (with the cover opening into it) are Myspoti's own.+ * sheet's drag to close. The full-bleed banner, Canvas clips, BitChord's track-swipe on the cover,+ * version switching, the lyric strip and the dock are left out. The landscape layout (cover beside+ * the controls), the Canvas behind the player (with the cover opening into it) and the swipe+ * along the cover that changes track (the mini player's) are Myspoti's own.*/package com.music.spotui.ui.immersive.player@@ -29,6 +30,8 @@ import androidx.compose.foundation.clickableimport androidx.compose.foundation.combinedClickableimport androidx.compose.foundation.gestures.awaitEachGestureimport androidx.compose.foundation.gestures.awaitFirstDown+import androidx.compose.foundation.gestures.awaitTouchSlopOrCancellation+import androidx.compose.foundation.gestures.dragimport androidx.compose.foundation.gestures.awaitVerticalTouchSlopOrCancellationimport androidx.compose.foundation.gestures.verticalDragimport androidx.compose.foundation.interaction.MutableInteractionSource@@ -116,6 +119,7 @@ import com.music.spotui.ui.components.SongBlendimport com.music.spotui.ui.components.SongBlendCoverimport com.music.spotui.ui.look.rememberArtworkColorsimport com.music.spotui.ui.look.rememberPauseScale+import kotlin.math.abs// Sizes and gaps of the portrait layout, as the player this follows has them.private val THUMB_SIZE = 54.dp@@ -191,6 +195,42 @@ internal fun Modifier.dragToClose(): Modifier {}}+/** How far the cover is swiped along to change track (the mini player's distance). */+private val TRACK_SWIPE_THRESHOLD = 72.dp++/**+ * A swipe along the cover changes track, as on the mini player: to the left the next song, to the+ * right the previous one, past [TRACK_SWIPE_THRESHOLD]. Only a mostly sideways move is taken (and+ * consumed); a vertical one is left untouched for [dragToClose] and a tap for the cover's click.+ * Off while [enabled] is false (the cover is the header's thumbnail under an open panel).+ */+@Composable+private fun Modifier.swipeToChangeTrack(enabled: Boolean, actions: ImmersivePlayerActions): Modifier {+ val on by rememberUpdatedState(enabled)+ val current by rememberUpdatedState(actions)+ return pointerInput(Unit) {+ val threshold = TRACK_SWIPE_THRESHOLD.toPx()+ awaitEachGesture {+ val down = awaitFirstDown(requireUnconsumed = false)+ if (!on) return@awaitEachGesture+ val slopped = awaitTouchSlopOrCancellation(down.id) { change, _ ->+ val moved = change.position - down.position+ if (abs(moved.x) > abs(moved.y)) change.consume()+ } ?: return@awaitEachGesture+ var dragged = (slopped.position - down.position).x+ val finished = drag(slopped.id) { change ->+ dragged += change.positionChange().x+ change.consume()+ }+ if (!finished) return@awaitEachGesture+ when {+ dragged <= -threshold -> current.next()+ dragged >= threshold -> current.previous()+ }+ }+ }+}+/*** The Immersive look's player: the cover's colours drifting behind a large cover, the credits,* a scrubber, the transport, the volume and a row of lyrics, devices and queue.@@ -381,6 +421,7 @@ fun ImmersivePlayer(}.background(Color.Black.copy(alpha = 0.18f)).dragToClose()+ .swipeToChangeTrack(enabled = panel == Panel.NONE, actions = actions).clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {if (panel != Panel.NONE) panel = Panel.NONE},@@ -444,7 +485,8 @@ fun ImmersivePlayer(.align(Alignment.CenterHorizontally),) {PlayerControlsBlock(- state = state, actions = actions, volume = volume, lyricsOpen = lyricsOpen, queueOpen = queueOpen, showVolume = true,+ state = state, actions = actions, volume = volume, lyricsOpen = lyricsOpen, queueOpen = queueOpen,+ showVolume = com.music.spotui.data.preferences.PlayerVolumePref.on,// Lyrics and the queue are two things to show in one place: opening one closes the other.onToggleLyrics = { panel = if (lyricsOpen) Panel.NONE else Panel.LYRICS },onToggleQueue = { panel = if (queueOpen) Panel.NONE else Panel.QUEUE },@@ -738,7 +780,8 @@ private fun LandscapePlayer(clip = true}.background(Color.Black.copy(alpha = 0.18f))- .dragToClose(),+ .dragToClose()+ .swipeToChangeTrack(enabled = true, actions = actions),) {GlideImage(model = state.coverUrl.takeIf { it.isNotBlank() },@@ -758,7 +801,7 @@ private fun LandscapePlayer(}BoxWithConstraints(Modifier.weight(1f).fillMaxHeight(), contentAlignment = Alignment.Center) {// The volume bar is the first thing to go when the window is low: the hardware keys do it too.- val showVolume = maxHeight >= LANDSCAPE_VOLUME_MIN_HEIGHT+ val showVolume = com.music.spotui.data.preferences.PlayerVolumePref.on && maxHeight >= LANDSCAPE_VOLUME_MIN_HEIGHTColumn(Modifier.widthIn(max = PLAYER_MAX_WIDTH).verticalScroll(rememberScrollState())) {Row(Modifier.fillMaxWidth().height(HEADER_HEIGHT), verticalAlignment = Alignment.CenterVertically) {PlayerCredits(state, actions, tint, scrolls = true, collapse = { 0f }, onMore = onMore, onSource = onSource, onSourceLong = onSourceLong)diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/EqualizerScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/EqualizerScreen.ktindex 5a0de03f..08ffdf8a 100644--- a/base/app/src/main/java/com/music/spotui/ui/screens/EqualizerScreen.kt+++ b/base/app/src/main/java/com/music/spotui/ui/screens/EqualizerScreen.kt@@ -37,6 +37,7 @@ import app.myspoti.engine.Rimport com.music.spotui.data.preferences.EqPresetimport com.music.spotui.data.preferences.EqualizerPrefimport com.music.spotui.di.EqBands+import com.music.spotui.di.Spatialimport com.music.spotui.ui.theme.AppAccentimport com.music.spotui.ui.theme.AppBackgroundimport com.music.spotui.ui.theme.AppMuted@@ -45,8 +46,8 @@ import com.music.spotui.ui.theme.tone/*** Settings > Playback > Equalizer (Classic): the local player's equalizer (on/off, a preset, ten- * bands and the preamp), its speed and silence skipping (see [EqualizerPref]). Says first what it- * applies to: never Spotify's own songs, whose sound the app does not get.+ * bands and the preamp), its spatial audio, speed and silence skipping (see [EqualizerPref]). Says+ * first what it applies to: never Spotify's own songs, whose sound the app does not get.*/@Composablefun EqualizerScreen(navController: NavController) {@@ -85,6 +86,25 @@ fun EqualizerScreen(navController: NavController) {modifier = Modifier.padding(horizontal = 8.dp, vertical = 6.dp).clip(RoundedCornerShape(50)).clickable(enabled = pref.enabled) { pref.setPreset(ctx, EqPreset.FLAT) }.padding(horizontal = 12.dp, vertical = 8.dp))+ Section(R.string.spatial_title)+ OptionRow(+ label = stringResource(R.string.spatial_enable),+ detail = stringResource(R.string.spatial_detail),+ checked = pref.spatial,+ onChecked = { pref.setSpatial(ctx, it) },+ )+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(horizontal = 20.dp)) {+ Text(stringResource(R.string.spatial_width), color = if (pref.spatial) AppText else AppMuted, fontSize = 13.sp, modifier = Modifier.width(64.dp))+ Slider(+ value = pref.spatialWidth, onValueChange = { pref.setSpatialWidth(ctx, widthStep(it), save = false) },+ onValueChangeFinished = { pref.setSpatialWidth(ctx, pref.spatialWidth) },+ valueRange = Spatial.MIN_WIDTH..Spatial.MAX_WIDTH, enabled = pref.spatial, modifier = Modifier.weight(1f),+ colors = SliderDefaults.colors(thumbColor = AppAccent, activeTrackColor = AppAccent, inactiveTrackColor = tone(0xFF3A3A3A)),+ )+ Text(widthText(pref.spatialWidth), color = AppMuted, fontSize = 12.sp,+ modifier = Modifier.width(64.dp).padding(start = 8.dp))+ }+Section(R.string.equalizer_section_playback)Column(Modifier.fillMaxWidth().padding(horizontal = 20.dp, vertical = 6.dp)) {Text(stringResource(R.string.equalizer_speed), color = AppText, fontSize = 16.sp)@@ -145,6 +165,13 @@ internal fun dbText(db: Float): String {return if (v > 0) "+$s" else s}+/** The spatial width in steps of 5 %. */+internal fun widthStep(width: Float): Float = Math.round(width * 20) / 20f++/** "160 %", "160%": the spatial width as a percentage, in the phone's language. */+internal fun widthText(width: Float): String =+ java.text.NumberFormat.getPercentInstance(java.util.Locale.getDefault()).format(widthStep(width).toDouble())+/** "1×", "1,25×" in the phone's language. */internal fun speedText(speed: Float): String = com.music.spotui.ui.components.speedLabel(speed.toDouble()) + "×"diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/PodcastPlayerScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/PodcastPlayerScreen.ktindex 054583ae..8742a457 100644--- a/base/app/src/main/java/com/music/spotui/ui/screens/PodcastPlayerScreen.kt+++ b/base/app/src/main/java/com/music/spotui/ui/screens/PodcastPlayerScreen.kt@@ -37,6 +37,7 @@ import androidx.compose.ui.Modifierimport androidx.compose.ui.draw.clipimport androidx.compose.ui.graphics.Brushimport androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.graphicsLayerimport androidx.compose.ui.layout.ContentScaleimport androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.res.painterResource@@ -61,6 +62,7 @@ import com.music.spotui.ui.components.QueueSheetimport com.music.spotui.ui.components.SleepTimerSheetimport com.music.spotui.ui.components.episodeClockimport com.music.spotui.ui.components.pressable+import com.music.spotui.ui.components.pullToDismissimport com.music.spotui.ui.components.speedLabelimport com.music.spotui.ui.theme.AppAccentimport com.music.spotui.ui.theme.AppBackground@@ -185,9 +187,13 @@ fun PodcastPlayerScreen(navController: NavController) {}val tint by androidx.compose.animation.animateColorAsState(coverColor, androidx.compose.animation.core.tween(450), label = "cover")+ // Pulled down anywhere, the player closes, as the music player does from the top of its list.+ val pullToClose = com.music.spotui.ui.components.rememberPullToDismiss { com.music.spotui.ui.navigation.PlayerSheet.close() }Box(Modifier.fillMaxSize()+ .pullToDismiss(pullToClose)+ .graphicsLayer { translationY = pullToClose.offset }.background(Brush.verticalGradient(listOf(tint, AppBackground))),) {Column(Modifier.fillMaxSize().statusBarsPadding()) {diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/SettingsScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/SettingsScreen.ktindex 6d5423d4..67ed6a91 100644--- a/base/app/src/main/java/com/music/spotui/ui/screens/SettingsScreen.kt+++ b/base/app/src/main/java/com/music/spotui/ui/screens/SettingsScreen.kt@@ -161,6 +161,25 @@ fun SettingsScreen(navController: NavController) {com.music.spotui.data.api.LyricsApi.forgetAll()},)+ // NetEase and Genius after Spotify and LRCLIB (also in the lyrics' own menu).+ var lyricsExtra by remember { mutableStateOf(com.music.spotui.data.preferences.isLyricsExtraSources(ctx)) }+ OptionRow(+ label = stringResource(R.string.lyrics_extra_title),+ detail = stringResource(R.string.lyrics_extra_summary),+ checked = lyricsExtra,+ onChecked = {+ lyricsExtra = it+ com.music.spotui.data.preferences.setLyricsExtraSources(ctx, it)+ com.music.spotui.data.api.LyricsApi.extraSources = it+ com.music.spotui.data.api.LyricsApi.forgetAll()+ },+ )+ OptionRow(+ label = stringResource(R.string.settings_lyrics_keep_awake_title),+ detail = stringResource(R.string.settings_lyrics_keep_awake_detail),+ checked = com.music.spotui.data.preferences.LyricsKeepAwakePref.on,+ onChecked = { com.music.spotui.data.preferences.LyricsKeepAwakePref.set(ctx, it) },+ )// Songs an extension streams, played by Spotify too (unheard): counted there, seen by Connect.if (com.music.spotui.extensions.Extensions.sources(app.myspoti.extensions.Action.AUDIO_SOURCE).isNotEmpty())OptionRow(diff --git a/base/app/src/test/java/com/music/spotui/di/SpatialProcessorTest.kt b/base/app/src/test/java/com/music/spotui/di/SpatialProcessorTest.ktnew file mode 100644index 00000000..3a3bc512--- /dev/null+++ b/base/app/src/test/java/com/music/spotui/di/SpatialProcessorTest.kt@@ -0,0 +1,151 @@+package com.music.spotui.di++import androidx.media3.common.C+import androidx.media3.common.audio.AudioProcessor+import org.junit.Assert.assertArrayEquals+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertTrue+import org.junit.Test+import java.nio.ByteBuffer+import java.nio.ByteOrder+import kotlin.math.PI+import kotlin.math.abs+import kotlin.math.roundToInt+import kotlin.math.sin+import kotlin.math.sqrt+[email protected](androidx.media3.common.util.UnstableApi::class)+class SpatialProcessorTest {+ private val rate = 44_100++ private fun processor(width: Float?, channels: Int = 2, encoding: Int = C.ENCODING_PCM_16BIT) =+ SpatialProcessor { width }.also {+ it.configure(AudioProcessor.AudioFormat(rate, channels, encoding))+ it.flush()+ }++ /** Stereo frames of a sine: [left] and [right] are each channel's amplitude (a negative one is the sine upside down). */+ private fun stereo(hz: Double, left: Double, right: Double, frames: Int): ShortArray =+ ShortArray(frames * 2) { i ->+ val v = sin(2 * PI * hz * (i / 2) / rate)+ ((if (i % 2 == 0) left else right) * 32767 * v).roundToInt().toShort()+ }++ /** Through the processor in buffers of 4096 frames, as the sink hands them. */+ private fun run(p: SpatialProcessor, input: ShortArray): ShortArray {+ val out = ArrayList<Short>(input.size)+ var at = 0+ while (at < input.size) {+ val n = minOf(4096 * 2, input.size - at)+ val buf = ByteBuffer.allocateDirect(n * 2).order(ByteOrder.nativeOrder())+ for (i in 0 until n) buf.putShort(input[at + i])+ buf.flip()+ p.queueInput(buf)+ assertFalse("all input consumed", buf.hasRemaining())+ val o = p.output+ while (o.hasRemaining()) out += o.short+ at += n+ }+ return out.toShortArray()+ }++ /** The RMS of one channel (0 left, 1 right) from frame [from]. */+ private fun rms(s: ShortArray, channel: Int, from: Int = 0): Double {+ var sum = 0.0+ var n = 0+ for (i in (from * 2 + channel) until s.size step 2) { sum += s[i].toDouble() * s[i]; n++ }+ return sqrt(sum / n)+ }++ private fun noise(n: Int): ShortArray { val r = java.util.Random(11); return ShortArray(n) { (r.nextInt(65536) - 32768).toShort() } }++ @Test fun offIsAnExactCopy() {+ val input = noise(2 * 20_000)+ assertArrayEquals(input, run(processor(null), input))+ }++ @Test fun widthOneIsAnExactCopy() {+ val input = noise(2 * 20_000)+ assertArrayEquals(input, run(processor(1f), input))+ }++ @Test fun floatOffIsAnExactCopy() {+ val p = processor(null, encoding = C.ENCODING_PCM_FLOAT)+ val buf = ByteBuffer.allocateDirect(4 * 1000).order(ByteOrder.nativeOrder())+ val r = java.util.Random(5)+ val values = FloatArray(1000) { r.nextFloat() * 2 - 1 }+ values.forEach(buf::putFloat); buf.flip()+ p.queueInput(buf)+ val o = p.output+ val back = FloatArray(1000) { o.float }+ assertArrayEquals(values, back, 0f)+ }++ @Test fun onlyStereoPcmIsProcessed() {+ val mono = SpatialProcessor { 2f }.apply { configure(AudioProcessor.AudioFormat(rate, 1, C.ENCODING_PCM_16BIT)) }+ assertFalse(mono.isActive)+ val surround = SpatialProcessor { 2f }.apply { configure(AudioProcessor.AudioFormat(rate, 6, C.ENCODING_PCM_16BIT)) }+ assertFalse(surround.isActive)+ val deep = SpatialProcessor { 2f }.apply { configure(AudioProcessor.AudioFormat(rate, 2, C.ENCODING_PCM_24BIT)) }+ assertFalse(deep.isActive)+ val float = SpatialProcessor { 2f }.apply { configure(AudioProcessor.AudioFormat(rate, 2, C.ENCODING_PCM_FLOAT)) }+ assertTrue(float.isActive)+ }++ @Test fun theCentreStaysCentredAndIsOnlyTurnedDown() {+ // The same sound in both ears (a centred voice): no side to widen, only the makeup gain.+ val input = stereo(440.0, 0.4, 0.4, rate / 4)+ val out = run(processor(2f), input)+ val gain = SpatialProcessor.makeup(2f)+ for (i in input.indices step 2) {+ assertEquals(out[i], out[i + 1])+ assertEquals(input[i] * gain.toDouble(), out[i].toDouble(), 1.0)+ }+ }++ @Test fun theSideIsRaisedByTheWidth() {+ // Opposite in each ear: all side, no mid. Width 2 doubles it, the makeup turns it down.+ val input = stereo(440.0, 0.2, -0.2, rate / 2)+ val out = run(processor(2f), input)+ val expected = 2 * SpatialProcessor.makeup(2f)+ assertEquals(expected.toDouble(), rms(out, 0) / rms(input, 0), 0.01)+ assertEquals(expected.toDouble(), rms(out, 1) / rms(input, 1), 0.01)+ }++ @Test fun aHardPannedPeakIsLimitedNotClipped() {+ // Left only, near full scale: the widest setting spills it far past full scale on both sides.+ val input = stereo(60.0, 0.98, 0.0, rate)+ val out = run(processor(Spatial.MAX_WIDTH), input)+ val peak = out.maxOf { abs(it.toInt()) }+ assertTrue("under the ceiling: $peak", peak <= (0.9886 * 32768).toInt() + 1)+ // The right channel now carries the inverted side: the image is wider, not just quieter.+ assertTrue(rms(out, 1, rate / 2) > 0.2 * rms(out, 0, rate / 2))+ }++ @Test fun turningOffGlidesThenCopies() {+ var width: Float? = 2f+ val p = SpatialProcessor { width }.also { it.configure(AudioProcessor.AudioFormat(rate, 2, C.ENCODING_PCM_16BIT)); it.flush() }+ run(p, stereo(440.0, 0.3, -0.1, rate / 4))+ width = null+ val input = noise(2 * 40_000)+ val out = run(p, input)+ // The width and the limiter glide back (full-scale noise keeps the limiter busy until the+ // width is 1), then the exact copy, well within half a second.+ val tail = 2 * 20_000+ assertArrayEquals(input.copyOfRange(tail, input.size), out.copyOfRange(tail, out.size))+ }++ @Test fun aChangeGlides() {+ var width: Float? = null+ val p = SpatialProcessor { width }.also { it.configure(AudioProcessor.AudioFormat(rate, 2, C.ENCODING_PCM_16BIT)); it.flush() }+ val input = stereo(440.0, 0.2, -0.2, rate / 2)+ run(p, input.copyOfRange(0, 2 * 4096))+ width = 2f+ val out = run(p, input.copyOfRange(2 * 4096, 2 * 8192))+ // The first frames after the switch are still close to the song as it was, not doubled at once.+ val firstPeak = (0 until 2 * 32).maxOf { abs(out[it].toInt()) }+ val inputPeak = (2 * 4096 until 2 * 4096 + 2 * 32).maxOf { abs(input[it].toInt()) }+ assertTrue("first $firstPeak vs $inputPeak", firstPeak <= inputPeak * 1.15)+ }+}