Skip to content

Native Android client for Spotify, built with Jetpack Compose

Equalizer for the songs the app plays itself (extensions, downloads, local files): a new Equalizer page in the playback settings of both looks and in the player's menu, with an on/off switch, fourteen presets, ten bands from 31 Hz to 16 kHz and a preamp, kept across launches, gliding without clicks, held under full scale by a limiter rather than clipped, and passing the sound bit for bit when off or flat; on the same page a speed from 0.5x to 2x and a Skip silences switch for everything the app plays (Spotify does not play a song along off 1x, a music video keeps up with the speed); the page says that Spotify's own songs and a Cast device are not changed. The equalizer's filters are adapted from BitChord (GPL-3.0-or-later) [skip ci]

kota-zod192f3877c23
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index 9c104a50..0a89de0f 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -33,6 +33,11 @@ PlayerQueue; `sharedUi/.../ui/components/` Common, SearchField, Skeletons, SongT
floatingtabbar/FloatingTabBar, floatingtabbar/GlassSelectionPill; `app/.../ui/player/PlayerSheetMotion`;
`app/.../ui/screens/` DetailScreen, LibraryPhoneParts; `app/.../ui/utils/IosOverscroll`.
+The local player's equalizer, `base/app/src/main/java/com/music/spotui/di/EqualizerProcessor.kt`, is
+adapted from BitChord's `app/src/main/java/com/music/bitchord/playback/EqualizerProcessor.kt` (commit
+`b690dc1`): its state-variable filter sections, their coefficients and the gliding of a change. It
+stays under the GPL-3.0-or-later and says so in its header.
+
No BitChord fonts, icons, images or brand are included.
Code that BitChord itself carries from other projects, kept with its own header:
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.kt
new file mode 100644
index 00000000..f54113ca
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/data/preferences/EqualizerPref.kt
@@ -0,0 +1,122 @@
+package com.music.spotui.data.preferences
+
+import android.content.Context
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.setValue
+import com.music.spotui.di.EqBands
+import com.music.spotui.di.EqTuning
+import com.music.spotui.di.Equalizer
+
+/** 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) {
+ FLAT(floatArrayOf(0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f), 0f),
+ BASS_BOOST(floatArrayOf(6f, 5f, 4f, 2f, 0f, 0f, 0f, 0f, 0f, 0f), -5f),
+ BASS_CUT(floatArrayOf(-6f, -5f, -4f, -2f, 0f, 0f, 0f, 0f, 0f, 0f), 0f),
+ TREBLE_BOOST(floatArrayOf(0f, 0f, 0f, 0f, 0f, 1f, 2f, 4f, 5f, 6f), -5f),
+ TREBLE_CUT(floatArrayOf(0f, 0f, 0f, 0f, 0f, -1f, -2f, -4f, -5f, -6f), 0f),
+ VOCAL(floatArrayOf(-2f, -2f, -1f, 0f, 2f, 4f, 4f, 2f, 0f, -1f), -3f),
+ ROCK(floatArrayOf(5f, 4f, 2f, -1f, -2f, -1f, 1f, 3f, 4f, 5f), -4f),
+ POP(floatArrayOf(-1f, 1f, 3f, 4f, 3f, 0f, -1f, -1f, 1f, 2f), -3f),
+ JAZZ(floatArrayOf(3f, 2f, 1f, 2f, -1f, -1f, 0f, 1f, 2f, 3f), -2f),
+ CLASSICAL(floatArrayOf(3f, 2f, 1f, 0f, 0f, 0f, -1f, -1f, 1f, 2f), -2f),
+ ELECTRONIC(floatArrayOf(5f, 4f, 1f, 0f, -2f, 1f, 0f, 1f, 4f, 5f), -4f),
+ HIP_HOP(floatArrayOf(5f, 4f, 2f, 3f, -1f, -1f, 1f, -1f, 2f, 3f), -4f),
+ ACOUSTIC(floatArrayOf(4f, 4f, 3f, 1f, 2f, 1f, 3f, 3f, 3f, 2f), -4f),
+ SPOKEN_WORD(floatArrayOf(-4f, -3f, 0f, 1f, 3f, 4f, 4f, 3f, 1f, -2f), -3f),
+ /** The user's own curve (a band or the preamp moved by hand). */
+ CUSTOM(FloatArray(10), 0f),
+}
+
+/**
+ * The equalizer, speed and silence skipping of the local player (ExoPlayer: extensions' streams,
+ * downloads, the phone's files). Spotify's own songs play in the Web Player, whose decoded sound
+ * the app never gets: none of this applies to them, nor to a Cast device. Kept across launches.
+ *
+ * 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.
+ */
+object EqualizerPref {
+ private const val PREF = "equalizer_prefs"
+ private fun prefs(c: Context) = c.getSharedPreferences(PREF, Context.MODE_PRIVATE)
+ private val p get() = prefs(com.music.spotui.di.Graph.app)
+
+ val SPEEDS = listOf(0.5f, 0.75f, 1f, 1.25f, 1.5f, 1.75f, 2f)
+
+ var enabled by mutableStateOf(p.getBoolean("enabled", false))
+ private set
+ var preset by mutableStateOf(runCatching { EqPreset.valueOf(p.getString("preset", null) ?: "FLAT") }.getOrDefault(EqPreset.FLAT))
+ private set
+ private var customGains by mutableStateOf(FloatArray(EqBands.COUNT) { p.getFloat("gain$it", 0f) })
+ private var customPreamp by mutableStateOf(p.getFloat("preamp", 0f))
+ var speed by mutableStateOf(p.getFloat("speed", 1f).coerceIn(0.5f, 2f))
+ private set
+ var skipSilence by mutableStateOf(p.getBoolean("skip_silence", false))
+ 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
+ val preamp: Float get() = if (preset == EqPreset.CUSTOM) customPreamp else preset.preamp
+
+ init { push() }
+
+ fun setEnabled(c: Context, on: Boolean) {
+ enabled = on
+ prefs(c).edit().putBoolean("enabled", on).apply()
+ push()
+ }
+
+ fun setPreset(c: Context, value: EqPreset) {
+ // Custom picked from the list: the curve last made by hand.
+ preset = value
+ prefs(c).edit().putString("preset", value.name).apply()
+ push()
+ }
+
+ /**
+ * A band moved by hand: the curve shown becomes the user's own, from where it was. Heard at
+ * once; kept when [save] (a slider saves once, at the end of its drag, see [save]).
+ */
+ fun setGain(c: Context, band: Int, db: Float, save: Boolean = true) {
+ if (band !in 0 until EqBands.COUNT) return
+ val g = gains.copyOf().also { it[band] = db.coerceIn(EqBands.MIN_DB, EqBands.MAX_DB) }
+ custom(c, g, preamp, save)
+ }
+
+ fun setPreamp(c: Context, db: Float, save: Boolean = true) =
+ custom(c, gains.copyOf(), db.coerceIn(EqBands.PREAMP_MIN_DB, EqBands.PREAMP_MAX_DB), save)
+
+ private fun custom(c: Context, g: FloatArray, pre: Float, save: Boolean) {
+ customGains = g; customPreamp = pre; preset = EqPreset.CUSTOM
+ push()
+ if (save) save(c)
+ }
+
+ /** Keeps the user's own curve as it is now. */
+ fun save(c: Context) {
+ prefs(c).edit().apply {
+ customGains.forEachIndexed { i, v -> putFloat("gain$i", v) }
+ putFloat("preamp", customPreamp); putString("preset", preset.name)
+ }.apply()
+ }
+
+ fun setSpeed(c: Context, value: Float) {
+ speed = value.coerceIn(0.5f, 2f)
+ prefs(c).edit().putFloat("speed", speed).apply()
+ com.music.spotui.di.LocalPlayer.applyPlayback()
+ // Spotify's page plays at 1× only: the mirror stops off 1×, and starts again at 1×.
+ com.music.spotui.di.ConnectMirror.settingChanged()
+ }
+
+ fun setSkipSilence(c: Context, on: Boolean) {
+ skipSilence = on
+ prefs(c).edit().putBoolean("skip_silence", on).apply()
+ com.music.spotui.di.LocalPlayer.applyPlayback()
+ }
+
+ /** Hands the curve to the players' equalizers (read on their audio threads). */
+ private fun push() {
+ Equalizer.current = if (enabled) EqTuning(gains, preamp) else null
+ }
+}
diff --git a/base/app/src/main/java/com/music/spotui/di/ConnectMirror.kt b/base/app/src/main/java/com/music/spotui/di/ConnectMirror.kt
index 2a2692e4..c4d388bf 100644
--- a/base/app/src/main/java/com/music/spotui/di/ConnectMirror.kt
+++ b/base/app/src/main/java/com/music/spotui/di/ConnectMirror.kt
@@ -174,6 +174,12 @@ object ConnectMirror {
val online = !download || com.music.spotui.data.offline.OfflineStore.isOnline(com.music.spotui.di.Graph.app)
// An extension that mirrors the download itself (playback.mirror) keeps the page, as before that setting.
val extensionHolds = download && (yieldedUri == uri || com.music.spotui.extensions.Extensions.mirror.active != null)
+ // Played off 1× (the equalizer's speed): Spotify's page plays music at 1× only, it would
+ // be put back every few seconds; the song plays alone, as with the setting off.
+ if (LocalPlayer.rate() != 1f) {
+ if (running) stop("the song plays at ${LocalPlayer.rate()}×, Spotify plays at 1× only")
+ return
+ }
if (extensionHolds || !MirrorRules.eligible(origin, id, ConnectMirrorPref.on, com.music.spotui.data.DataSaver.active, DownloadSyncPref.on, online)) {
if (running) stop(if (origin == MirrorRules.Origin.AUDIO_SOURCE) "not mirrored: ${t.title}" else "a download or a file of the phone plays")
return
diff --git a/base/app/src/main/java/com/music/spotui/di/EqualizerProcessor.kt b/base/app/src/main/java/com/music/spotui/di/EqualizerProcessor.kt
new file mode 100644
index 00000000..66ba1c6c
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/di/EqualizerProcessor.kt
@@ -0,0 +1,249 @@
+/*
+ * Adapted from BitChord (https://github.com/kushagrasinghx/BitChord), GPL-3.0-or-later,
+ * app/src/main/java/com/music/bitchord/playback/EqualizerProcessor.kt at b690dc1.
+ * Modified for Myspoti, 2026-10.
+ *
+ * Changes: the trapezoidal state-variable sections (shelves at both ends, bells between),
+ * their coefficients and the gliding of a change are BitChord's; the bands are Myspoti's ten
+ * (31 Hz to 16 kHz), the tone controls, balance and loudness stage are left out, the float
+ * path and an exact copy when the curve is flat are added, and the limiter is a small one of
+ * our own.
+ */
+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.min
+import kotlin.math.pow
+import kotlin.math.roundToInt
+import kotlin.math.sqrt
+import kotlin.math.tan
+
+/** The equalizer's bands and its ranges (see [EqualizerProcessor]). */
+object EqBands {
+ /** The centre of each band, in Hz: the first is a low shelf, the last a high shelf, bells between. */
+ val FREQUENCIES = floatArrayOf(31f, 62f, 125f, 250f, 500f, 1_000f, 2_000f, 4_000f, 8_000f, 16_000f)
+ val COUNT = FREQUENCIES.size
+ const val MIN_DB = -12f
+ const val MAX_DB = 12f
+ const val PREAMP_MIN_DB = -12f
+ const val PREAMP_MAX_DB = 12f
+}
+
+/** A curve: the gain of each band and the preamp, in dB. Swapped whole, never changed in place. */
+class EqTuning(gainsDb: FloatArray, val preampDb: Float) {
+ val gainsDb: FloatArray = FloatArray(EqBands.COUNT) { gainsDb.getOrElse(it) { 0f }.coerceIn(EqBands.MIN_DB, EqBands.MAX_DB) }
+ /** Nothing to hear: the audio passes as it came, bit for bit. */
+ val flat: Boolean get() = abs(preampDb) < SETTLED_DB && gainsDb.all { abs(it) < SETTLED_DB }
+
+ companion object {
+ internal const val SETTLED_DB = 0.01f
+ }
+}
+
+/** The curve the local player's equalizers follow; null: off (see EqualizerPref). Read on the audio thread. */
+object Equalizer {
+ @Volatile var current: EqTuning? = null
+}
+
+/**
+ * The equalizer of the local player (extensions' streams, downloads, the phone's files): a
+ * media3 audio processor in ExoPlayer's chain, ahead of the silence skipping and the speed. Each
+ * player has its own (the fading-out copy of a crossfade too), all following [source].
+ *
+ * Off, or on with a flat curve (every band and the preamp at 0 dB), it copies its input as it
+ * came: a lossless stream stays bit for bit what the extension gave. A change glides over a few
+ * milliseconds rather than stepping (no click); a curve that would push a peak past full scale is
+ * caught by a peak limiter at -0.1 dBFS rather than clipped. 16-bit and float PCM; anything else
+ * passes untouched (the processor is then inactive).
+ */
+@UnstableApi
+class EqualizerProcessor(private val source: () -> EqTuning? = { Equalizer.current }) : BaseAudioProcessor() {
+ private val slots = EqBands.COUNT
+ private var channels = 0
+ private var sampleRate = 0
+ private var float = false
+
+ private val currentGain = FloatArray(slots)
+ private var currentPreamp = 0f
+ private val a1 = FloatArray(slots)
+ private val a2 = FloatArray(slots)
+ private val a3 = FloatArray(slots)
+ private val m0 = FloatArray(slots)
+ private val m1 = FloatArray(slots)
+ private val m2 = FloatArray(slots)
+ private val active = IntArray(slots)
+ private val running = BooleanArray(slots)
+ /** Two integrator states per band and channel. */
+ private var state = FloatArray(0)
+ private var frame = FloatArray(0)
+ private var limiterGain = 1f
+ private var release = 0f
+ private var holdFrames = 0
+ private var holdLeft = 0
+
+ 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 < 1 || inputAudioFormat.sampleRate <= 0)
+ return AudioProcessor.AudioFormat.NOT_SET
+ channels = inputAudioFormat.channelCount
+ sampleRate = inputAudioFormat.sampleRate
+ float = enc == C.ENCODING_PCM_FLOAT
+ state = FloatArray(channels * slots * 2)
+ frame = FloatArray(channels)
+ // Held 50 ms after a peak (longer than a period of the lowest band), then back up in about 200 ms.
+ holdFrames = sampleRate / 20
+ release = 1f - kotlin.math.exp(-1f / (0.2f * sampleRate))
+ return inputAudioFormat
+ }
+
+ override fun onFlush() {
+ state.fill(0f); running.fill(false); limiterGain = 1f; holdLeft = 0
+ // A new stream (or a seek) starts on the curve, not gliding to it.
+ val t = source()
+ for (i in 0 until slots) currentGain[i] = t?.gainsDb?.get(i) ?: 0f
+ currentPreamp = t?.preampDb ?: 0f
+ }
+
+ override fun onReset() {
+ channels = 0; sampleRate = 0; state = FloatArray(0); frame = FloatArray(0)
+ }
+
+ override fun queueInput(inputBuffer: ByteBuffer) {
+ if (!inputBuffer.hasRemaining()) return
+ val target = source()?.takeUnless { it.flat }
+ if (target == null && settledFlat()) {
+ // The exact copy: nothing heard is changed, nothing computed.
+ if (running.any { it }) { state.fill(0f); running.fill(false) }
+ limiterGain = 1f; holdLeft = 0
+ val out = replaceOutputBuffer(inputBuffer.remaining())
+ out.put(inputBuffer)
+ out.flip()
+ return
+ }
+ val bytes = if (float) 4 else 2
+ val frameBytes = bytes * channels
+ val frames = inputBuffer.remaining() / frameBytes
+ if (frames == 0) return
+ val out = replaceOutputBuffer(frames * frameBytes)
+ inputBuffer.order(ByteOrder.nativeOrder())
+ val gains = target?.gainsDb
+ val preampTarget = target?.preampDb ?: 0f
+ var left = frames
+ while (left > 0) {
+ val block = min(left, GLIDE_FRAMES)
+ for (i in 0 until slots) currentGain[i] += ((gains?.get(i) ?: 0f) - currentGain[i]) * GLIDE_RATE
+ currentPreamp += (preampTarget - currentPreamp) * GLIDE_RATE
+ val n = prepare()
+ val preamp = 10f.pow(currentPreamp / 20f)
+ repeat(block) {
+ var peak = 0f
+ for (c in 0 until channels) {
+ var s = if (float) inputBuffer.float else inputBuffer.short * (1f / 32768f)
+ for (k in 0 until n) s = section(active[k], c, s)
+ s *= preamp
+ frame[c] = s
+ if (abs(s) > peak) peak = abs(s)
+ }
+ // The limiter: down at once to what keeps this frame under the ceiling, held while
+ // the peaks stay near it (a crest after another is turned down, not flattened), then
+ // back up slowly.
+ val need = if (peak > CEILING) CEILING / peak else 1f
+ if (peak * limiterGain > CEILING * HOLD_NEAR) holdLeft = holdFrames
+ else if (holdLeft > 0) holdLeft--
+ else limiterGain += (1f - limiterGain) * release
+ limiterGain = min(need, limiterGain)
+ for (c in 0 until channels) {
+ val s = frame[c] * limiterGain
+ if (float) out.putFloat(s) else out.putShort((s * 32768f).roundToInt().coerceIn(-32768, 32767).toShort())
+ }
+ }
+ flushDenormals(n)
+ left -= block
+ }
+ out.flip()
+ }
+
+ /** No band and no preamp left to glide down: the copy can take over. */
+ private fun settledFlat(): Boolean =
+ abs(currentPreamp) < EqTuning.SETTLED_DB && currentGain.all { abs(it) < EqTuning.SETTLED_DB }
+
+ /** The coefficients of the bands that do something now; their count (indices in [active]). */
+ private fun prepare(): Int {
+ var n = 0
+ for (i in 0 until slots) {
+ if (abs(currentGain[i]) >= EqTuning.SETTLED_DB) {
+ coefficients(i)
+ active[n++] = i
+ running[i] = true
+ } else if (running[i]) {
+ for (c in 0 until channels) { val j = (c * slots + i) * 2; state[j] = 0f; state[j + 1] = 0f }
+ running[i] = false
+ }
+ }
+ return n
+ }
+
+ private fun coefficients(i: Int) {
+ val a = 10f.pow(currentGain[i] / 40f)
+ val hz = EqBands.FREQUENCIES[i].coerceIn(10f, sampleRate * 0.45f)
+ val base = tan(Math.PI * hz / sampleRate).toFloat()
+ val g: Float
+ val k: Float
+ when (i) {
+ 0 -> { // low shelf
+ g = base / sqrt(a); k = 1f / SHELF_Q
+ m0[i] = 1f; m1[i] = k * (a - 1f); m2[i] = a * a - 1f
+ }
+ slots - 1 -> { // high shelf
+ g = base * sqrt(a); k = 1f / SHELF_Q
+ m0[i] = a * a; m1[i] = k * (1f - a) * a; m2[i] = 1f - a * a
+ }
+ else -> { // bell
+ g = base; k = 1f / (BELL_Q * a)
+ m0[i] = 1f; m1[i] = k * (a * a - 1f); m2[i] = 0f
+ }
+ }
+ val d = 1f / (1f + g * (g + k))
+ a1[i] = d; a2[i] = g * d; a3[i] = g * g * d
+ }
+
+ private fun section(i: Int, c: Int, x: Float): Float {
+ val j = (c * slots + i) * 2
+ val ic1 = state[j]
+ val ic2 = state[j + 1]
+ val v3 = x - ic2
+ val v1 = a1[i] * ic1 + a2[i] * v3
+ val v2 = ic2 + a2[i] * ic1 + a3[i] * v3
+ state[j] = 2f * v1 - ic1
+ state[j + 1] = 2f * v2 - ic2
+ return m0[i] * x + m1[i] * v1 + m2[i] * v2
+ }
+
+ private fun flushDenormals(n: Int) {
+ for (k in 0 until n) for (c in 0 until channels) {
+ val j = (c * slots + active[k]) * 2
+ if (abs(state[j]) < 1e-12f) state[j] = 0f
+ if (abs(state[j + 1]) < 1e-12f) state[j + 1] = 0f
+ }
+ }
+
+ private companion object {
+ /** Frames between two steps of a glide (about 1.5 ms at 44.1 kHz). */
+ const val GLIDE_FRAMES = 64
+ /** The part of what is left of a change made at each step (about 18 ms to get there). */
+ const val GLIDE_RATE = 0.08f
+ /** About an octave wide. */
+ const val BELL_Q = 1.41f
+ const val SHELF_Q = 0.707f
+ /** -0.1 dBFS. */
+ const val CEILING = 0.9886f
+ /** Peaks within 0.5 dB of the ceiling keep the limiter's gain where it is. */
+ const val HOLD_NEAR = 0.944f
+ }
+}
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.kt
index 338a64bd..bb1e29b1 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
@@ -61,7 +61,7 @@ object LocalPlayer {
}
@androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)
- private fun build(main: Boolean): ExoPlayer = ExoPlayer.Builder(Graph.app)
+ private fun build(main: Boolean): ExoPlayer = ExoPlayer.Builder(Graph.app, Renderers)
// The fading-out copy of a crossfade owns neither the audio focus nor the noisy-audio pause:
// the main player has them and the fade follows its play state.
.setAudioAttributes(audioAttributes, main && !mirrorActive)
@@ -70,6 +70,37 @@ object LocalPlayer {
.setMediaSourceFactory(androidx.media3.exoplayer.source.DefaultMediaSourceFactory(
com.music.spotui.data.offline.OfflineCrypto.Factory(Graph.app)).setLoadErrorHandlingPolicy(NoAudioNotRetried))
.build()
+ // The speed and the silence skipping of the settings (the fading-out copy too: both are heard).
+ .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.
+ */
+ @androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)
+ private object Renderers : androidx.media3.exoplayer.DefaultRenderersFactory(Graph.app) {
+ override fun buildAudioSink(context: android.content.Context, enableFloatOutput: Boolean, enableAudioTrackPlaybackParams: Boolean): androidx.media3.exoplayer.audio.AudioSink =
+ androidx.media3.exoplayer.audio.DefaultAudioSink.Builder(context)
+ .setEnableFloatOutput(enableFloatOutput)
+ .setEnableAudioTrackPlaybackParams(enableAudioTrackPlaybackParams)
+ .setAudioProcessors(arrayOf(EqualizerProcessor()))
+ .build()
+ }
+
+ private fun tune(p: ExoPlayer) {
+ val pref = com.music.spotui.data.preferences.EqualizerPref
+ if (p.playbackParameters.speed != pref.speed) p.playbackParameters = androidx.media3.common.PlaybackParameters(pref.speed)
+ if (p.skipSilenceEnabled != pref.skipSilence) p.skipSilenceEnabled = pref.skipSilence
+ }
+
+ /** The speed or the silence skipping changed in the settings: the song playing (and a fade) takes it now. */
+ fun applyPlayback() {
+ exo?.let(::tune); outgoing?.let(::tune)
+ log("speed ${rate()}×, skip silences ${if (com.music.spotui.data.preferences.EqualizerPref.skipSilence) "on" else "off"}")
+ }
+
+ /** The speed the local player plays at (the settings', 1 by default). */
+ fun rate(): Float = com.music.spotui.data.preferences.EqualizerPref.speed
@androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)
private fun player(): ExoPlayer = exo ?: build(true).also { p ->
diff --git a/base/app/src/main/java/com/music/spotui/ui/components/SongOptionsSheet.kt b/base/app/src/main/java/com/music/spotui/ui/components/SongOptionsSheet.kt
index fd509337..085f2434 100644
--- a/base/app/src/main/java/com/music/spotui/ui/components/SongOptionsSheet.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/components/SongOptionsSheet.kt
@@ -44,6 +44,7 @@ import androidx.compose.material.icons.outlined.Block
import androidx.compose.material.icons.outlined.Bookmark
import androidx.compose.material.icons.outlined.Delete
import androidx.compose.material.icons.outlined.Speed
+import androidx.compose.material.icons.outlined.GraphicEq
import androidx.compose.material.icons.outlined.ThumbDownOffAlt
import kotlinx.coroutines.launch
import androidx.compose.material3.ExperimentalMaterial3Api
@@ -316,6 +317,13 @@ fun SongOptionsSheet(
if (nowPlaying && song.url.startsWith("episode:")) {
MenuRow(Icons.Outlined.Speed, stringResource(R.string.playback_speed)) { showSpeed = true }
}
+ // The app's own playback (extensions, downloads, files): its equalizer, speed and silences.
+ if (nowPlaying && com.music.spotui.di.LocalPlayer.active.value) {
+ MenuRow(Icons.Outlined.GraphicEq, stringResource(R.string.equalizer_title)) {
+ onDismiss()
+ navController.navigate(com.music.spotui.ui.navigation.Routes.Equalizer.route)
+ }
+ }
MenuRow(Icons.Outlined.Share, stringResource(R.string.context_menu_share), enabled = hasId) {
SpotifyCode.show(ShareTarget("spotify:track:${song.spotifyTrackId}", song.title, song.singer, song.coverUri))
onDismiss()
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.kt
new file mode 100644
index 00000000..b57ca679
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveEqualizerScreen.kt
@@ -0,0 +1,115 @@
+package com.music.spotui.ui.immersive.pages
+
+import androidx.activity.compose.BackHandler
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.heightIn
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.width
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.saveable.rememberSaveable
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.text.style.TextAlign
+import androidx.compose.ui.unit.dp
+import androidx.navigation.NavController
+import app.myspoti.engine.R
+import com.music.spotui.data.preferences.EqPreset
+import com.music.spotui.data.preferences.EqualizerPref
+import com.music.spotui.di.EqBands
+import com.music.spotui.ui.immersive.Immersive
+import com.music.spotui.ui.look.ThinSlider
+import com.music.spotui.ui.screens.dbText
+import com.music.spotui.ui.screens.eqBandLabel
+import com.music.spotui.ui.screens.eqPresetLabel
+import com.music.spotui.ui.screens.speedText
+
+/**
+ * Settings > Playback > Equalizer (Immersive): the Classic page's settings (see EqualizerScreen)
+ * in grouped cards; the preset opens its list as a page of its own.
+ */
+@Composable
+fun ImmersiveEqualizerScreen(navController: NavController) {
+ val ctx = LocalContext.current
+ val pref = EqualizerPref
+ var presets by rememberSaveable { mutableStateOf(false) }
+ if (presets) {
+ BackHandler { presets = false }
+ ImmersivePage(title = stringResource(R.string.equalizer_preset), onBack = { presets = false }) {
+ immersiveGroup("presets") {
+ for (p in EqPreset.entries.filter { it != EqPreset.CUSTOM || pref.preset == EqPreset.CUSTOM }) row {
+ ImmersiveChoiceRow(stringResource(eqPresetLabel(p)), selected = pref.preset == p,
+ onClick = { pref.setPreset(ctx, p); presets = false })
+ }
+ }
+ }
+ return
+ }
+ ImmersivePage(title = stringResource(R.string.equalizer_title), onBack = { navController.popBackStack() }) {
+ immersiveBlock("scope") {
+ Text(stringResource(R.string.equalizer_scope), style = Immersive.Caption, textAlign = TextAlign.Start)
+ }
+ immersiveGroup("eq", footerRes = R.string.equalizer_enable_detail) {
+ row { ImmersiveSwitchRow(stringResource(R.string.equalizer_enable), checked = pref.enabled, onChecked = { pref.setEnabled(ctx, it) }) }
+ row {
+ ImmersiveGroupRow(stringResource(R.string.equalizer_preset), value = stringResource(eqPresetLabel(pref.preset)),
+ chevron = true, enabled = pref.enabled, onClick = { presets = true })
+ }
+ }
+ immersiveGroup("bands", headerRes = R.string.equalizer_bands, footerRes = R.string.equalizer_preamp_detail) {
+ val gains = pref.gains
+ for (band in 0 until EqBands.COUNT) row {
+ DbRow(eqBandLabel(band), gains[band], EqBands.MIN_DB, EqBands.MAX_DB, pref.enabled,
+ onChange = { pref.setGain(ctx, band, it, save = false) }, onDone = { pref.save(ctx) })
+ }
+ row {
+ DbRow(stringResource(R.string.equalizer_preamp), pref.preamp, EqBands.PREAMP_MIN_DB, EqBands.PREAMP_MAX_DB, pref.enabled,
+ onChange = { pref.setPreamp(ctx, it, save = false) }, onDone = { pref.save(ctx) })
+ }
+ row {
+ ImmersiveGroupRow(stringResource(R.string.equalizer_reset), enabled = pref.enabled,
+ onClick = { pref.setPreset(ctx, EqPreset.FLAT) })
+ }
+ }
+ immersiveGroup("speed", headerRes = R.string.equalizer_speed, footerRes = R.string.equalizer_speed_detail) {
+ row {
+ ImmersiveSegmentedControl(
+ options = EqualizerPref.SPEEDS.map(::speedText),
+ selectedIndex = EqualizerPref.SPEEDS.indexOf(pref.speed).coerceAtLeast(0),
+ onSelect = { pref.setSpeed(ctx, EqualizerPref.SPEEDS[it]) },
+ modifier = Modifier.padding(12.dp),
+ )
+ }
+ }
+ immersiveGroup("silences") {
+ row {
+ ImmersiveSwitchRow(stringResource(R.string.equalizer_skip_silence), checked = pref.skipSilence,
+ onChecked = { pref.setSkipSilence(ctx, it) }, detail = stringResource(R.string.equalizer_skip_silence_detail))
+ }
+ }
+ }
+}
+
+/** One band (or the preamp): its name, the look's thin slider in 0.5 dB steps, its gain. */
+@Composable
+private fun DbRow(label: String, value: Float, min: Float, max: Float, enabled: Boolean, onChange: (Float) -> Unit, onDone: () -> Unit) {
+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp).padding(horizontal = 16.dp)) {
+ Text(label, style = Immersive.Body.copy(color = if (enabled) Immersive.Text else Immersive.TextTertiary), modifier = Modifier.width(64.dp))
+ ThinSlider(
+ value = (value - min) / (max - min),
+ onValueChange = { if (enabled) onChange(Math.round((min + it * (max - min)) * 2) / 2f) },
+ onValueChangeFinished = onDone,
+ modifier = Modifier.weight(1f),
+ activeColor = if (enabled) Immersive.Accent else Immersive.TextTertiary,
+ )
+ Spacer(Modifier.width(10.dp))
+ Text(stringResource(R.string.equalizer_db, dbText(value)), style = Immersive.Caption, modifier = Modifier.width(56.dp), textAlign = TextAlign.End)
+ }
+}
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.kt
index 1e35ff87..87859fd9 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
@@ -240,6 +240,14 @@ private fun PlaybackPage(navController: NavController, open: (SettingsPage) -> U
chevron = true, onClick = { open(SettingsPage.Crossfade) },
)
}
+ // The local player's equalizer, speed and silence skipping (never Spotify's own songs).
+ row {
+ ImmersiveGroupRow(
+ stringResource(R.string.equalizer_title), detail = stringResource(R.string.equalizer_settings_detail),
+ value = if (com.music.spotui.data.preferences.EqualizerPref.enabled) stringResource(com.music.spotui.ui.screens.eqPresetLabel(com.music.spotui.data.preferences.EqualizerPref.preset)) else null,
+ chevron = true, onClick = { navController.navigate(Routes.Equalizer.route) },
+ )
+ }
row {
ImmersiveSwitchRow(
stringResource(R.string.settings_keep_playing_title), checked = keepPlaying,
diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/sheets/ImmersiveSongOptionsSheet.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/sheets/ImmersiveSongOptionsSheet.kt
index 71f44310..71a08fd6 100644
--- a/base/app/src/main/java/com/music/spotui/ui/immersive/sheets/ImmersiveSongOptionsSheet.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/sheets/ImmersiveSongOptionsSheet.kt
@@ -29,6 +29,7 @@ import androidx.compose.material.icons.rounded.Share
import androidx.compose.material.icons.rounded.SortByAlpha
import androidx.compose.material.icons.rounded.SwapHoriz
import androidx.compose.material.icons.rounded.Speed
+import androidx.compose.material.icons.rounded.GraphicEq
import androidx.compose.material.icons.rounded.ThumbDownOffAlt
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
@@ -300,6 +301,13 @@ fun ImmersiveSongOptionsSheet(
if (nowPlaying && song.url.startsWith("episode:")) {
ImmersiveSheetRow(Icons.Rounded.Speed, stringResource(R.string.playback_speed)) { showSpeed = true }
}
+ // The app's own playback (extensions, downloads, files): its equalizer, speed and silences.
+ if (nowPlaying && com.music.spotui.di.LocalPlayer.active.value) {
+ ImmersiveSheetRow(Icons.Rounded.GraphicEq, stringResource(R.string.equalizer_title)) {
+ onDismiss()
+ navController.navigate(com.music.spotui.ui.navigation.Routes.Equalizer.route)
+ }
+ }
ImmersiveSheetRow(Icons.Rounded.Share, stringResource(R.string.context_menu_share), enabled = hasId) {
SpotifyCode.show(ShareTarget("spotify:track:${song.spotifyTrackId}", song.title, song.singer, song.coverUri))
onDismiss()
diff --git a/base/app/src/main/java/com/music/spotui/ui/navigation/MyNavHost.kt b/base/app/src/main/java/com/music/spotui/ui/navigation/MyNavHost.kt
index 815a277b..9d57ea37 100644
--- a/base/app/src/main/java/com/music/spotui/ui/navigation/MyNavHost.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/navigation/MyNavHost.kt
@@ -152,6 +152,15 @@ fun MyNavHost(
if (isImmersive()) com.music.spotui.ui.immersive.pages.ImmersiveHiddenSongsScreen(navHostController) else com.music.spotui.ui.screens.HiddenSongsScreen(navHostController)
}
+ // The local player's equalizer, speed and silence skipping (Settings > Playback, the player's menu).
+ page(Routes.Equalizer.route) {
+ LaunchedEffect(playerState) {
+ bottomBarState.value = true
+ bottomBarPlayerState.value = playerState != ""
+ }
+ if (isImmersive()) com.music.spotui.ui.immersive.pages.ImmersiveEqualizerScreen(navHostController) else com.music.spotui.ui.screens.EqualizerScreen(navHostController)
+ }
+
page(Routes.NewReleases.route) {
LaunchedEffect(playerState) {
bottomBarState.value = true
diff --git a/base/app/src/main/java/com/music/spotui/ui/navigation/Routes.kt b/base/app/src/main/java/com/music/spotui/ui/navigation/Routes.kt
index 1b1c7bd4..268e89be 100644
--- a/base/app/src/main/java/com/music/spotui/ui/navigation/Routes.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/navigation/Routes.kt
@@ -25,6 +25,7 @@ sealed class Routes(
object LocalFiles : Routes(0, "LocalFiles", "localfiles")
object Downloads : Routes(0, "Downloads", "downloads")
object HiddenSongs : Routes(0, "HiddenSongs", "hiddensongs")
+ object Equalizer : Routes(0, "Equalizer", "equalizer")
object Folder : Routes(0, "Folder", "folder")
object LocalPlaylist : Routes(0, "LocalPlaylist", "localplaylist")
object Category : Routes(0, "Category", "category")
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.kt
new file mode 100644
index 00000000..5a0de03f
--- /dev/null
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/EqualizerScreen.kt
@@ -0,0 +1,175 @@
+package com.music.spotui.ui.screens
+
+import androidx.compose.foundation.background
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.horizontalScroll
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.navigationBarsPadding
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.statusBarsPadding
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.automirrored.filled.ArrowBack
+import androidx.compose.material3.Icon
+import androidx.compose.material3.IconButton
+import androidx.compose.material3.Slider
+import androidx.compose.material3.SliderDefaults
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import androidx.navigation.NavController
+import app.myspoti.engine.R
+import com.music.spotui.data.preferences.EqPreset
+import com.music.spotui.data.preferences.EqualizerPref
+import com.music.spotui.di.EqBands
+import com.music.spotui.ui.theme.AppAccent
+import com.music.spotui.ui.theme.AppBackground
+import com.music.spotui.ui.theme.AppMuted
+import com.music.spotui.ui.theme.AppText
+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.
+ */
+@Composable
+fun EqualizerScreen(navController: NavController) {
+ val ctx = LocalContext.current
+ val pref = EqualizerPref
+ Column(Modifier.fillMaxSize().background(AppBackground).statusBarsPadding()) {
+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(4.dp)) {
+ IconButton(onClick = { navController.popBackStack() }) {
+ Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.accessibility_navigate_back), tint = AppText)
+ }
+ Text(stringResource(R.string.equalizer_title), color = AppText, fontSize = 20.sp, fontWeight = FontWeight.Bold)
+ }
+ Column(Modifier.fillMaxWidth().weight(1f).verticalScroll(rememberScrollState()).navigationBarsPadding()) {
+ Text(stringResource(R.string.equalizer_scope), color = AppMuted, fontSize = 12.sp,
+ modifier = Modifier.padding(horizontal = 20.dp, vertical = 8.dp))
+ OptionRow(
+ label = stringResource(R.string.equalizer_enable),
+ detail = stringResource(R.string.equalizer_enable_detail),
+ checked = pref.enabled,
+ onChecked = { pref.setEnabled(ctx, it) },
+ )
+ Section(R.string.equalizer_preset)
+ Chips(EqPreset.entries.filter { it != EqPreset.CUSTOM || pref.preset == EqPreset.CUSTOM }, { it == pref.preset },
+ { stringResource(eqPresetLabel(it)) }, enabled = pref.enabled) { pref.setPreset(ctx, it) }
+ Section(R.string.equalizer_bands)
+ val gains = pref.gains
+ for (band in 0 until EqBands.COUNT) {
+ DbSlider(eqBandLabel(band), gains[band], EqBands.MIN_DB..EqBands.MAX_DB, pref.enabled,
+ onChange = { pref.setGain(ctx, band, it, save = false) }, onDone = { pref.save(ctx) })
+ }
+ DbSlider(stringResource(R.string.equalizer_preamp), pref.preamp, EqBands.PREAMP_MIN_DB..EqBands.PREAMP_MAX_DB, pref.enabled,
+ onChange = { pref.setPreamp(ctx, it, save = false) }, onDone = { pref.save(ctx) })
+ Text(stringResource(R.string.equalizer_preamp_detail), color = AppMuted, fontSize = 12.sp,
+ modifier = Modifier.padding(horizontal = 20.dp))
+ Text(stringResource(R.string.equalizer_reset), color = if (pref.enabled) AppAccent else AppMuted, fontSize = 14.sp, fontWeight = FontWeight.Bold,
+ 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.equalizer_section_playback)
+ Column(Modifier.fillMaxWidth().padding(horizontal = 20.dp, vertical = 6.dp)) {
+ Text(stringResource(R.string.equalizer_speed), color = AppText, fontSize = 16.sp)
+ Text(stringResource(R.string.equalizer_speed_detail), color = AppMuted, fontSize = 12.sp, modifier = Modifier.padding(top = 2.dp))
+ }
+ Chips(EqualizerPref.SPEEDS, { it == pref.speed }, { speedText(it) }) { pref.setSpeed(ctx, it) }
+ OptionRow(
+ label = stringResource(R.string.equalizer_skip_silence),
+ detail = stringResource(R.string.equalizer_skip_silence_detail),
+ checked = pref.skipSilence,
+ onChecked = { pref.setSkipSilence(ctx, it) },
+ )
+ }
+ }
+}
+
+/** A row of choices as the crossfade's, scrolling sideways when they do not fit. */
+@Composable
+private fun <T> Chips(items: List<T>, selected: (T) -> Boolean, label: @Composable (T) -> String, enabled: Boolean = true, onPick: (T) -> Unit) {
+ Row(
+ horizontalArrangement = Arrangement.spacedBy(8.dp),
+ modifier = Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).padding(horizontal = 20.dp, vertical = 8.dp),
+ ) {
+ for (item in items) {
+ val on = selected(item)
+ Text(
+ label(item),
+ color = if (on) Color.Black else if (enabled) AppText else AppMuted, fontSize = 14.sp,
+ modifier = Modifier.clip(RoundedCornerShape(50))
+ .background(if (on && enabled) AppAccent else if (on) AppMuted else tone(0xFF2A2A2A))
+ .clickable(enabled = enabled) { onPick(item) }
+ .padding(horizontal = 14.dp, vertical = 8.dp),
+ )
+ }
+ }
+}
+
+/** One band (or the preamp): its name, a slider in 0.5 dB steps and its gain. */
+@Composable
+private fun DbSlider(label: String, value: Float, range: ClosedFloatingPointRange<Float>, enabled: Boolean,
+ onChange: (Float) -> Unit, onDone: () -> Unit) {
+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(horizontal = 20.dp)) {
+ Text(label, color = if (enabled) AppText else AppMuted, fontSize = 13.sp, modifier = Modifier.width(64.dp))
+ Slider(
+ value = value, onValueChange = { onChange((it * 2).let(Math::round) / 2f) }, onValueChangeFinished = onDone,
+ valueRange = range, enabled = enabled, modifier = Modifier.weight(1f),
+ colors = SliderDefaults.colors(thumbColor = AppAccent, activeTrackColor = AppAccent, inactiveTrackColor = tone(0xFF3A3A3A)),
+ )
+ Text(stringResource(R.string.equalizer_db, dbText(value)), color = AppMuted, fontSize = 12.sp,
+ modifier = Modifier.width(64.dp).padding(start = 8.dp))
+ }
+}
+
+/** "+3", "0", "-1.5": a gain as both looks show it. */
+internal fun dbText(db: Float): String {
+ val v = Math.round(db * 2) / 2f
+ val s = if (v == Math.floor(v.toDouble()).toFloat()) v.toInt().toString() else String.format(java.util.Locale.getDefault(), "%.1f", v)
+ return if (v > 0) "+$s" else s
+}
+
+/** "1×", "1,25×" in the phone's language. */
+internal fun speedText(speed: Float): String = com.music.spotui.ui.components.speedLabel(speed.toDouble()) + "×"
+
+/** "31 Hz", "1 kHz", "16 kHz". */
+@Composable
+internal fun eqBandLabel(band: Int): String {
+ val hz = EqBands.FREQUENCIES[band]
+ return if (hz >= 1000f) stringResource(R.string.equalizer_khz, com.music.spotui.ui.components.speedLabel(hz / 1000.0))
+ else stringResource(R.string.equalizer_hz, hz.toInt().toString())
+}
+
+internal fun eqPresetLabel(p: EqPreset): Int = when (p) {
+ EqPreset.FLAT -> R.string.eq_preset_flat
+ EqPreset.BASS_BOOST -> R.string.eq_preset_bass_boost
+ EqPreset.BASS_CUT -> R.string.eq_preset_bass_cut
+ EqPreset.TREBLE_BOOST -> R.string.eq_preset_treble_boost
+ EqPreset.TREBLE_CUT -> R.string.eq_preset_treble_cut
+ EqPreset.VOCAL -> R.string.eq_preset_vocal
+ EqPreset.ROCK -> R.string.eq_preset_rock
+ EqPreset.POP -> R.string.eq_preset_pop
+ EqPreset.JAZZ -> R.string.eq_preset_jazz
+ EqPreset.CLASSICAL -> R.string.eq_preset_classical
+ EqPreset.ELECTRONIC -> R.string.eq_preset_electronic
+ EqPreset.HIP_HOP -> R.string.eq_preset_hip_hop
+ EqPreset.ACOUSTIC -> R.string.eq_preset_acoustic
+ EqPreset.SPOKEN_WORD -> R.string.eq_preset_spoken_word
+ EqPreset.CUSTOM -> R.string.eq_preset_custom
+}
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.kt
index c2a78960..16182d3d 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
@@ -117,6 +117,14 @@ fun SettingsScreen(navController: NavController) {
onChecked = { com.music.spotui.data.preferences.AppShufflePref.set(ctx, it) },
)
CrossfadeRow()
+ // The local player's equalizer, speed and silence skipping (never Spotify's own songs).
+ Column(
+ Modifier.fillMaxWidth().clickable { navController.navigate(com.music.spotui.ui.navigation.Routes.Equalizer.route) }
+ .padding(horizontal = 20.dp, vertical = 10.dp),
+ ) {
+ Text(stringResource(R.string.equalizer_title), color = AppText, fontSize = 16.sp)
+ Text(stringResource(R.string.equalizer_settings_detail), color = AppMuted, fontSize = 12.sp)
+ }
var keepPlaying by remember { mutableStateOf(app.myspoti.host.android.PlaybackService.keepsPlayingOnClose(ctx)) }
OptionRow(
label = stringResource(R.string.settings_keep_playing_title),
@@ -358,7 +366,7 @@ private fun SourcesBlock(action: app.myspoti.extensions.Action, navController: N
}
@Composable
-private fun Section(title: Int) {
+internal fun Section(title: Int) {
Text(stringResource(title).uppercase(), color = com.music.spotui.ui.theme.AppAccent, fontSize = 12.sp, fontWeight = FontWeight.Bold,
letterSpacing = 1.sp, modifier = Modifier.padding(start = 20.dp, end = 20.dp, top = 16.dp, bottom = 8.dp))
}
@@ -570,7 +578,7 @@ private fun RemoveDownloadsRow() {
@Composable
-private fun OptionRow(label: String, detail: String, checked: Boolean,
+internal fun OptionRow(label: String, detail: String, checked: Boolean,
enabled: Boolean = true, onChecked: (Boolean) -> Unit) {
Row(verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().heightIn(min = 64.dp)
diff --git a/base/app/src/main/java/com/music/spotui/video/MusicVideoController.kt b/base/app/src/main/java/com/music/spotui/video/MusicVideoController.kt
index a4fa70bf..a3b97bca 100644
--- a/base/app/src/main/java/com/music/spotui/video/MusicVideoController.kt
+++ b/base/app/src/main/java/com/music/spotui/video/MusicVideoController.kt
@@ -873,8 +873,10 @@ object MusicVideoController {
!com.music.spotui.di.LocalPlayer.active.value
hush(sounding)
p.volume = if (hushed) 1f else 0f
+ // The song's own speed (the local player's setting; Spotify's songs play at 1×): the clip keeps up with it.
+ val rate = if (com.music.spotui.di.LocalPlayer.active.value) com.music.spotui.di.LocalPlayer.rate() else 1f
if (!shown) {
- if (p.playbackParameters.speed != 1f) p.playbackParameters = PlaybackParameters(1f)
+ if (p.playbackParameters.speed != rate) p.playbackParameters = PlaybackParameters(rate)
delay(500)
continue
}
@@ -887,14 +889,14 @@ object MusicVideoController {
// reported): seen only, a drift under 2.5 s is caught up by speed instead.
(if (hushed) abs(drift) > 600 else abs(drift) > 2_500) -> {
Logbook.log("clip: ${drift} ms off at ${SongPlayer.getCurrentPosition()} ms of the song, put back")
- p.seekTo(target); p.playbackParameters = PlaybackParameters(1f)
+ p.seekTo(target); p.playbackParameters = PlaybackParameters(rate)
}
// Heard, the clip is corrected gently (a 10 % change is heard); seen only, firmly.
- hushed && abs(drift) > 120 -> p.playbackParameters = PlaybackParameters((1f - drift / 4000f).coerceIn(0.97f, 1.03f))
- hushed -> if (p.playbackParameters.speed != 1f && abs(drift) < 40) p.playbackParameters = PlaybackParameters(1f)
- playing && abs(drift) > 600 -> p.playbackParameters = PlaybackParameters((1f - drift / 2000f).coerceIn(0.6f, 1.5f))
- playing && abs(drift) > 40 -> p.playbackParameters = PlaybackParameters((1f - drift / 2000f).coerceIn(0.9f, 1.1f))
- p.playbackParameters.speed != 1f -> p.playbackParameters = PlaybackParameters(1f)
+ hushed && abs(drift) > 120 -> p.playbackParameters = PlaybackParameters(rate * (1f - drift / 4000f).coerceIn(0.97f, 1.03f))
+ hushed -> if (p.playbackParameters.speed != rate && abs(drift) < 40) p.playbackParameters = PlaybackParameters(rate)
+ playing && abs(drift) > 600 -> p.playbackParameters = PlaybackParameters(rate * (1f - drift / 2000f).coerceIn(0.6f, 1.5f))
+ playing && abs(drift) > 40 -> p.playbackParameters = PlaybackParameters(rate * (1f - drift / 2000f).coerceIn(0.9f, 1.1f))
+ p.playbackParameters.speed != rate -> p.playbackParameters = PlaybackParameters(rate)
}
}
delay(150)
diff --git a/base/app/src/main/res/values/myspoti_strings.xml b/base/app/src/main/res/values/myspoti_strings.xml
index f0f58838..fef37e4e 100644
--- a/base/app/src/main/res/values/myspoti_strings.xml
+++ b/base/app/src/main/res/values/myspoti_strings.xml
@@ -624,4 +624,37 @@
<string name="lan_logging_in">Logging in…</string>
<string name="lan_failed">%1$s did not accept the login. Open it once with the Spotify app, then try again.</string>
<string name="lan_others">%1$d more on this network need the Spotify app to log them in first</string>
+ <string name="equalizer_title">Equalizer</string>
+ <string name="equalizer_settings_detail">Equalizer, speed and silence skipping for songs from extensions, downloads and local files</string>
+ <string name="equalizer_scope">For songs from extensions, downloads and local files, which the app plays itself. Spotify\'s own songs play in Spotify\'s web player, whose sound the app cannot reach: nothing on this page changes them, nor what plays on a Cast device.</string>
+ <string name="equalizer_enable">Use the equalizer</string>
+ <string name="equalizer_enable_detail">Off, or with every band at 0 dB, the sound passes untouched (a lossless stream stays lossless).</string>
+ <string name="equalizer_preset">Preset</string>
+ <string name="equalizer_bands">Bands</string>
+ <string name="equalizer_preamp">Preamp</string>
+ <string name="equalizer_preamp_detail">Lowers or raises everything. A boost close to full scale is held back by a limiter rather than clipped.</string>
+ <string name="equalizer_reset">Reset to flat</string>
+ <string name="equalizer_db">%1$s dB</string>
+ <string name="equalizer_hz">%1$s Hz</string>
+ <string name="equalizer_khz">%1$s kHz</string>
+ <string name="eq_preset_flat">Flat</string>
+ <string name="eq_preset_bass_boost">Bass boost</string>
+ <string name="eq_preset_bass_cut">Bass cut</string>
+ <string name="eq_preset_treble_boost">Treble boost</string>
+ <string name="eq_preset_treble_cut">Treble cut</string>
+ <string name="eq_preset_vocal">Vocal</string>
+ <string name="eq_preset_rock">Rock</string>
+ <string name="eq_preset_pop">Pop</string>
+ <string name="eq_preset_jazz">Jazz</string>
+ <string name="eq_preset_classical">Classical</string>
+ <string name="eq_preset_electronic">Electronic</string>
+ <string name="eq_preset_hip_hop">Hip-hop</string>
+ <string name="eq_preset_acoustic">Acoustic</string>
+ <string name="eq_preset_spoken_word">Spoken word</string>
+ <string name="eq_preset_custom">Custom</string>
+ <string name="equalizer_section_playback">Speed and silences</string>
+ <string name="equalizer_speed">Speed</string>
+ <string name="equalizer_speed_detail">Everything the app plays itself, music and downloaded episodes alike. Episodes streamed by Spotify keep the podcast player\'s speed. At any speed but 1×, Spotify does not play the song along (it is not counted there and your other devices do not see it): Spotify plays music at 1× only.</string>
+ <string name="equalizer_skip_silence">Skip silences</string>
+ <string name="equalizer_skip_silence_detail">Silent stretches are skipped (long pauses in an episode, a silence before a hidden track).</string>
</resources>
diff --git a/base/app/src/test/java/com/music/spotui/di/EqualizerProcessorTest.kt b/base/app/src/test/java/com/music/spotui/di/EqualizerProcessorTest.kt
new file mode 100644
index 00000000..b5006e85
--- /dev/null
+++ b/base/app/src/test/java/com/music/spotui/di/EqualizerProcessorTest.kt
@@ -0,0 +1,156 @@
+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.log10
+import kotlin.math.roundToInt
+import kotlin.math.sin
+import kotlin.math.sqrt
+
[email protected](androidx.media3.common.util.UnstableApi::class)
+class EqualizerProcessorTest {
+ private val rate = 44_100
+
+ private fun processor(tuning: EqTuning?, channels: Int = 2, encoding: Int = C.ENCODING_PCM_16BIT) =
+ EqualizerProcessor { tuning }.also {
+ it.configure(AudioProcessor.AudioFormat(rate, channels, encoding))
+ it.flush()
+ }
+
+ private fun sine(hz: Double, amplitude: Double, frames: Int, channels: Int = 2): ShortArray =
+ ShortArray(frames * channels) { i -> (amplitude * 32767 * sin(2 * PI * hz * (i / channels) / rate)).roundToInt().toShort() }
+
+ /** Through the processor in buffers of 4096 frames, as the sink hands them. */
+ private fun run(p: EqualizerProcessor, input: ShortArray, channels: Int = 2): ShortArray {
+ val out = ArrayList<Short>(input.size)
+ var at = 0
+ while (at < input.size) {
+ val n = minOf(4096 * channels, 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()
+ }
+
+ private fun rms(s: ShortArray, from: Int): Double {
+ var sum = 0.0
+ for (i in from until s.size) sum += s[i].toDouble() * s[i]
+ return sqrt(sum / (s.size - from))
+ }
+
+ private fun db(ratio: Double) = 20 * log10(ratio)
+
+ private fun noise(n: Int): ShortArray { val r = java.util.Random(7); 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 flatIsAnExactCopy() {
+ val input = noise(2 * 20_000)
+ assertArrayEquals(input, run(processor(EqTuning(FloatArray(10), 0f)), 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(3)
+ 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 otherEncodingsPassUntouched() {
+ val p = EqualizerProcessor { EqTuning(FloatArray(10) { 6f }, 0f) }
+ p.configure(AudioProcessor.AudioFormat(rate, 2, C.ENCODING_PCM_24BIT))
+ assertFalse(p.isActive)
+ }
+
+ @Test fun oneBandRaisesItsFrequencyOnly() {
+ val gains = FloatArray(10).also { it[5] = 6f } // 1 kHz
+ val frames = rate // a second
+ val atBand = sine(1000.0, 0.2, frames)
+ val raised = run(processor(EqTuning(gains, 0f)), atBand)
+ assertEquals(6.0, db(rms(raised, 2 * 4410) / rms(atBand, 2 * 4410)), 0.3)
+ // Three octaves below, the bell does next to nothing.
+ val far = sine(125.0, 0.2, frames)
+ val kept = run(processor(EqTuning(gains, 0f)), far)
+ assertEquals(0.0, db(rms(kept, 2 * 4410) / rms(far, 2 * 4410)), 0.3)
+ }
+
+ @Test fun shelvesAtTheEnds() {
+ val gains = FloatArray(10).also { it[0] = -6f; it[9] = 6f }
+ // Below the low shelf's corner, toward its full cut; above the high one's, toward its boost.
+ val low = sine(10.0, 0.2, rate)
+ val lowDb = db(rms(run(processor(EqTuning(gains, 0f)), low), 2 * 4410) / rms(low, 2 * 4410))
+ assertTrue("low shelf $lowDb dB", lowDb in -6.5..-4.0)
+ val high = sine(20_000.0, 0.2, rate)
+ val highDb = db(rms(run(processor(EqTuning(gains, 0f)), high), 2 * 4410) / rms(high, 2 * 4410))
+ assertTrue("high shelf $highDb dB", highDb in 3.0..6.5)
+ // In the middle, neither.
+ val mid = sine(1000.0, 0.2, rate)
+ assertEquals(0.0, db(rms(run(processor(EqTuning(gains, 0f)), mid), 2 * 4410) / rms(mid, 2 * 4410)), 0.3)
+ }
+
+ @Test fun preampScalesEverything() {
+ val input = sine(440.0, 0.5, rate / 4)
+ val out = run(processor(EqTuning(FloatArray(10), -6.0206f)), input)
+ // Started on the curve (no glide at the start of a stream): half, to the rounding.
+ for (i in input.indices) assertEquals(input[i] / 2.0, out[i].toDouble(), 1.0)
+ }
+
+ @Test fun aBoostNearFullScaleIsLimitedNotClipped() {
+ val gains = FloatArray(10) { if (it < 3) 12f else 0f }
+ val input = sine(60.0, 0.95, rate)
+ val out = run(processor(EqTuning(gains, 0f)), input)
+ val peak = out.maxOf { abs(it.toInt()) }
+ assertTrue("under the ceiling: $peak", peak <= (0.9886 * 32768).toInt() + 1)
+ // Clipping flattens the tops: runs of the same extreme sample (four times over full scale,
+ // a clipped sine sits there over a third of the time: thousands in half a second). A
+ // limited one keeps its shape: at most a pair or two equal at each crest, from the rounding
+ // to 16 bits (60 crests in half a second at 60 Hz).
+ val half = out.copyOfRange(out.size / 2, out.size) // past the filters' own settling
+ val top = half.maxOf { abs(it.toInt()) }
+ var flat = 0
+ for (i in 2 until half.size step 2) if (abs(half[i].toInt()) >= top - 1 && half[i] == half[i - 2]) flat++
+ assertTrue("tops kept round ($flat flat)", flat <= 2 * 60)
+ }
+
+ @Test fun monoWorks() {
+ val gains = FloatArray(10).also { it[5] = -6f }
+ val input = sine(1000.0, 0.3, rate / 2, channels = 1)
+ val out = run(processor(EqTuning(gains, 0f), channels = 1), input, channels = 1)
+ assertEquals(-6.0, db(rms(out, 4410) / rms(input, 4410)), 0.3)
+ }
+
+ @Test fun turningOffGlidesThenCopies() {
+ var tuning: EqTuning? = EqTuning(FloatArray(10).also { it[5] = 6f }, -3f)
+ val p = EqualizerProcessor { tuning }.also { it.configure(AudioProcessor.AudioFormat(rate, 2, C.ENCODING_PCM_16BIT)); it.flush() }
+ run(p, sine(1000.0, 0.2, rate / 4))
+ tuning = null
+ val input = noise(2 * 20_000)
+ val out = run(p, input)
+ // A few milliseconds of glide, then the exact copy.
+ val tail = 2 * 10_000
+ assertArrayEquals(input.copyOfRange(tail, input.size), out.copyOfRange(tail, out.size))
+ }
+}