Harden the playback service and make next/previous work outside the app

- Resolve every item from a controller against the station list: an item
  without a URI (voice requests from Assistant or Android Auto) no longer
  crashes the player, and other apps can no longer start arbitrary streams.
- Offer next/previous to the notification, headset buttons and Android Auto
  through a ForwardingSimpleBasePlayer that switches the station; the player
  still holds only the station on air, so no other stream is prepared.
- Do not spend reconnect attempts while offline; reconnect when the network
  comes back instead of pausing for good after about four minutes.
- Swiping the app away during an error or a pending reconnect stops the
  service; a short rebuffer while playing does not.
- Loudness Enhancer applies a 6 dB boost by default; the old default of 0
  made the switch do nothing. The unused gain setter chain is removed.
- Count station switches made outside the app in recents and play counts.
This commit is contained in:
2026-11-12 16:43:34 +02:00
parent ac19416c00
commit 8cd9133803
10 changed files with 181 additions and 112 deletions
@@ -1,20 +0,0 @@
package cc.skysparkle.fogwave
import android.app.Application
import coil.ImageLoader
import coil.ImageLoaderFactory
import coil.memory.MemoryCache
class FogwaveApp : Application(), ImageLoaderFactory {
override fun newImageLoader(): ImageLoader {
return ImageLoader.Builder(this)
.memoryCache {
MemoryCache.Builder(this)
.maxSizePercent(0.20)
.build()
}
.crossfade(true)
.respectCacheHeaders(false)
.build()
}
}
@@ -42,11 +42,6 @@ object AudioEffectsController {
refresh()
}
fun setLoudnessGain(gainMillibel: Float) {
engine?.setLoudnessGain(gainMillibel)
refresh()
}
fun setDynamicsProcessingEnabled(enabled: Boolean) {
engine?.setDynamicsProcessingEnabled(enabled)
refresh()
@@ -25,8 +25,6 @@ data class AudioEffectsState(
val currentPreset: Int = -1,
val loudnessAvailable: Boolean = false,
val loudnessEnabled: Boolean = false,
val loudnessGainMillibel: Float = 0f,
val loudnessMaxGainMillibel: Float = 2000f,
val dynamicsProcessingAvailable: Boolean = false,
val dynamicsProcessingEnabled: Boolean = false
)
@@ -52,7 +50,10 @@ class AudioEffectsEngine(context: Context, audioSessionId: Int) {
private var equalizerEnabled = prefs.getBoolean(KEY_EQ_ENABLED, false)
private var loudnessEnabled = prefs.getBoolean(KEY_LOUDNESS_ENABLED, false)
private var loudnessGain = prefs.getInt(KEY_LOUDNESS_GAIN, 0).coerceIn(0, MAX_LOUDNESS_GAIN)
// There is no gain slider, so the switch applies a fixed, moderate boost. A gain of 0 (the old
// default) made the switch do nothing.
private val loudnessGain = prefs.getInt(KEY_LOUDNESS_GAIN, DEFAULT_LOUDNESS_GAIN)
.takeIf { it > 0 }?.coerceAtMost(MAX_LOUDNESS_GAIN) ?: DEFAULT_LOUDNESS_GAIN
private var dynamicsEnabled = prefs.getBoolean(KEY_DYNAMICS_ENABLED, false)
init {
@@ -178,7 +179,6 @@ class AudioEffectsEngine(context: Context, audioSessionId: Int) {
currentPreset = if (eqAvailable) currentPresetIndex else -1,
loudnessAvailable = loudnessEnhancer != null,
loudnessEnabled = loudnessEnhancer != null && loudnessEnabled,
loudnessGainMillibel = if (loudnessEnhancer != null) loudnessGain.toFloat() else 0f,
dynamicsProcessingAvailable = dynamicsProcessing != null,
dynamicsProcessingEnabled = dynamicsProcessing != null && dynamicsEnabled
)
@@ -233,17 +233,6 @@ class AudioEffectsEngine(context: Context, audioSessionId: Int) {
} catch (_: Exception) {}
}
fun setLoudnessGain(gainMillibel: Float) {
val le = loudnessEnhancer ?: return
val gain = gainMillibel.coerceIn(0f, MAX_LOUDNESS_GAIN.toFloat()).toInt()
if (gain == loudnessGain) return
try {
le.setTargetGain(gain)
loudnessGain = gain
prefs.edit { putInt(KEY_LOUDNESS_GAIN, gain) }
} catch (_: Exception) {}
}
fun setDynamicsProcessingEnabled(enabled: Boolean) {
val dp = dynamicsProcessing ?: return
try {
@@ -265,6 +254,7 @@ class AudioEffectsEngine(context: Context, audioSessionId: Int) {
private companion object {
const val TAG = "AudioEffectsEngine"
const val MAX_LOUDNESS_GAIN = 2000
const val DEFAULT_LOUDNESS_GAIN = 600
const val KEY_EQ_ENABLED = "eq_enabled"
const val KEY_PRESET = "eq_preset"
const val KEY_BAND_PREFIX = "eq_band_"
@@ -15,13 +15,13 @@ import android.util.Log
import androidx.annotation.OptIn
import androidx.media3.common.AudioAttributes
import androidx.media3.common.C
import androidx.media3.common.ForwardingSimpleBasePlayer
import androidx.media3.common.MediaItem
import androidx.media3.common.MediaMetadata
import androidx.media3.common.PlaybackException
import androidx.media3.common.Player
import androidx.media3.common.util.UnstableApi
import androidx.media3.datasource.DefaultHttpDataSource
import androidx.media3.datasource.HttpDataSource
import androidx.media3.exoplayer.DefaultLoadControl
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.exoplayer.source.DefaultMediaSourceFactory
@@ -33,6 +33,7 @@ import androidx.media3.session.MediaSession
import cc.skysparkle.fogwave.BuildConfig
import cc.skysparkle.fogwave.MainActivity
import cc.skysparkle.fogwave.R
import cc.skysparkle.fogwave.data.model.RadioStation
import cc.skysparkle.fogwave.data.repository.RadioRepository
import com.google.common.collect.ImmutableList
import com.google.common.util.concurrent.Futures
@@ -50,6 +51,10 @@ class FogwavePlaybackService : MediaLibraryService() {
private var mediaLibrarySession: MediaLibrarySession? = null
private lateinit var repository: RadioRepository
private lateinit var player: ExoPlayer
// Station order for next/previous from the notification, a headset or the car; sorted once,
// like the grid in the app.
private var stationOrder: List<RadioStation> = emptyList()
private var audioEffectsEngine: AudioEffectsEngine? = null
private val serviceScope = CoroutineScope(Dispatchers.Main.immediate + SupervisorJob())
@@ -66,6 +71,11 @@ class FogwavePlaybackService : MediaLibraryService() {
private var connectivityManager: ConnectivityManager? = null
private var networkCallback: ConnectivityManager.NetworkCallback? = null
private var defaultNetwork: Network? = null
private var hasNetwork = true
// Set when a reconnect is due but there is no network: no attempts are spent while offline,
// the stream is reopened from onAvailable instead.
private var waitingForNetwork = false
// ExoPlayer drops its own wake and Wi-Fi locks once the player is idle after an error, so the
// backoff delay would stall while the CPU sleeps. These are held only while a reconnect is pending.
@@ -136,30 +146,94 @@ class FogwavePlaybackService : MediaLibraryService() {
return Futures.immediateFuture(LibraryResult.ofItem(station.toMediaItem(this@FogwavePlaybackService), null))
}
// Items coming from a controller are never trusted: only the mediaId (or a voice search
// query) is read, and the stream URI always comes from our own station list. Without this
// an item without a URI (a voice request from Assistant or Android Auto) crashed the
// player, and any app on the device could make Fogwave play an arbitrary stream.
override fun onAddMediaItems(
mediaSession: MediaSession,
controller: MediaSession.ControllerInfo,
mediaItems: MutableList<MediaItem>
): ListenableFuture<MutableList<MediaItem>> {
val resolved = mediaItems.map { item ->
if (item.localConfiguration != null) {
item
} else {
repository.stations.find { it.id == item.mediaId }
?.toMediaItem(this@FogwavePlaybackService)
?: item
val resolved = mediaItems.map { resolveStation(it).toMediaItem(this@FogwavePlaybackService) }
.toMutableList()
resolved.firstOrNull()?.let { onNewRequest(it) }
return Futures.immediateFuture(resolved)
}
}
}.toMutableList()
resolved.firstOrNull()?.let { item ->
Log.d(TAG, "MediaItem resolved: mediaId=${item.mediaId} uri=${item.localConfiguration?.uri}")
private fun resolveStation(item: MediaItem): RadioStation {
val stations = repository.stations
val query = item.requestMetadata.searchQuery?.trim().orEmpty()
return stations.find { it.id == item.mediaId }
?: query.takeIf { it.isNotEmpty() }?.let { q ->
stations.find { it.name.contains(q, ignoreCase = true) }
?: stations.find { q.contains(it.name, ignoreCase = true) }
}
?: stations.find { it.id == repository.getLastStationId() }
?: stations.first()
}
private fun onNewRequest(item: MediaItem) {
Log.d(TAG, "MediaItem resolved: mediaId=${item.mediaId}")
lastRequestedItem = item
retryJob?.cancel()
retryAttempt = 0
waitingForNetwork = false
}
return Futures.immediateFuture(resolved)
private fun switchStation(step: Int) {
val order = stationOrder.ifEmpty { repository.stations }
val currentId = player.currentMediaItem?.mediaId ?: lastRequestedItem?.mediaId
val index = order.indexOfFirst { it.id == currentId }
val target = if (index < 0) order.first() else order[(index + step).mod(order.size)]
Log.d(TAG, "Switching station: ${target.id}")
val item = target.toMediaItem(this)
onNewRequest(item)
repository.setLastStationId(target.id)
// playWhenReady is kept: a paused player switches the station and stays paused.
player.setMediaItem(item)
player.prepare()
}
/**
* The player only ever holds the station that is on air: with the whole list in ExoPlayer every
* stream would be prepared at once, and the HLS ones would keep refreshing their playlists in
* the background. Instead next/previous are always offered to the session (notification,
* headset buttons, Android Auto) and switch the station here, wrapping around like the app.
*/
private inner class StationSwitchingPlayer(player: Player) : ForwardingSimpleBasePlayer(player) {
override fun getState(): State {
val state = super.getState()
if (state.timeline.isEmpty()) return state
val commands = state.availableCommands.buildUpon()
.addAll(
Player.COMMAND_SEEK_TO_NEXT,
Player.COMMAND_SEEK_TO_NEXT_MEDIA_ITEM,
Player.COMMAND_SEEK_TO_PREVIOUS,
Player.COMMAND_SEEK_TO_PREVIOUS_MEDIA_ITEM
)
.remove(Player.COMMAND_SET_REPEAT_MODE)
.build()
// REPEAT_MODE_ALL makes next/previous resolve to the single item, which lands in
// handleSeek below with the original seek command.
return state.buildUpon()
.setAvailableCommands(commands)
.setRepeatMode(Player.REPEAT_MODE_ALL)
.build()
}
override fun handleSeek(mediaItemIndex: Int, positionMs: Long, seekCommand: Int): ListenableFuture<*> {
when (seekCommand) {
Player.COMMAND_SEEK_TO_NEXT, Player.COMMAND_SEEK_TO_NEXT_MEDIA_ITEM -> switchStation(+1)
Player.COMMAND_SEEK_TO_PREVIOUS, Player.COMMAND_SEEK_TO_PREVIOUS_MEDIA_ITEM -> switchStation(-1)
else -> return super.handleSeek(mediaItemIndex, positionMs, seekCommand)
}
return Futures.immediateVoidFuture()
}
// The stream's own repeat mode stays off; a dropped stream is handled by scheduleReconnect.
override fun handleSetRepeatMode(repeatMode: Int): ListenableFuture<*> = Futures.immediateVoidFuture()
}
private val resiliencePlayerListener = object : Player.Listener {
@@ -196,6 +270,7 @@ class FogwavePlaybackService : MediaLibraryService() {
Log.d(TAG, "Reconnect cancelled - playWhenReady=false (reason=$reason)")
}
retryJob?.cancel()
waitingForNetwork = false
releaseReconnectLocks()
pausedAtMs = SystemClock.elapsedRealtime()
return
@@ -225,25 +300,16 @@ class FogwavePlaybackService : MediaLibraryService() {
}
}
// A missing stream or an unsupported format will not fix itself, so it gets only a couple of
// attempts (a stale token or a short server outage can still recover); network errors get the full backoff.
private fun maxRetryAttemptsFor(error: PlaybackException): Int {
val httpCode = (error.cause as? HttpDataSource.InvalidResponseCodeException)?.responseCode
val permanent = when (error.errorCode) {
PlaybackException.ERROR_CODE_IO_BAD_HTTP_STATUS ->
httpCode != null && httpCode in 400..499 && httpCode != 408 && httpCode != 429
PlaybackException.ERROR_CODE_IO_FILE_NOT_FOUND,
PlaybackException.ERROR_CODE_IO_CLEARTEXT_NOT_PERMITTED,
PlaybackException.ERROR_CODE_PARSING_CONTAINER_UNSUPPORTED,
PlaybackException.ERROR_CODE_PARSING_MANIFEST_UNSUPPORTED,
PlaybackException.ERROR_CODE_DECODING_FORMAT_UNSUPPORTED -> true
else -> false
}
return if (permanent) MAX_PERMANENT_ERROR_RETRY_ATTEMPTS else MAX_RETRY_ATTEMPTS
}
private fun scheduleReconnect(immediate: Boolean = false, maxAttempts: Int = MAX_RETRY_ATTEMPTS) {
retryJob?.cancel()
if (!immediate && !hasNetwork) {
// Attempts would only fail and run out while offline; wait for onAvailable instead.
Log.d(TAG, "No network - waiting for it before reconnecting")
waitingForNetwork = true
releaseReconnectLocks()
return
}
waitingForNetwork = false
if (!immediate && retryAttempt >= maxAttempts) {
// Give up instead of keeping the device busy forever; the error stays visible and a tap
// on play starts over.
@@ -316,13 +382,23 @@ class FogwavePlaybackService : MediaLibraryService() {
private fun registerNetworkCallback() {
val cm = getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager ?: return
connectivityManager = cm
hasNetwork = cm.activeNetwork != null
val callback = object : ConnectivityManager.NetworkCallback() {
// Called on a ConnectivityManager thread; ExoPlayer must only be accessed on the main thread.
override fun onAvailable(network: Network) {
serviceScope.launch {
val previous = defaultNetwork
defaultNetwork = network
hasNetwork = true
val wasWaiting = waitingForNetwork
waitingForNetwork = false
if (!player.playWhenReady || player.playbackState == Player.STATE_READY) return@launch
if (wasWaiting) {
Log.d(TAG, "Network is back - reconnecting")
retryAttempt = 0
scheduleReconnect(immediate = true)
return@launch
}
// After a switch (e.g. Wi-Fi to mobile) a stalled load can sit on a dead socket until
// the read timeout, so reopen right away instead of waiting for the error.
val switchedWhileStalled = previous != null && previous != network &&
@@ -333,6 +409,13 @@ class FogwavePlaybackService : MediaLibraryService() {
}
}
}
override fun onLost(network: Network) {
serviceScope.launch {
// A switch reports the new network first; only the loss of the current one counts.
if (network == defaultNetwork) hasNetwork = false
}
}
}
networkCallback = callback
try {
@@ -344,6 +427,7 @@ class FogwavePlaybackService : MediaLibraryService() {
override fun onCreate() {
super.onCreate()
repository = RadioRepository(applicationContext)
stationOrder = repository.stationsSortedByPopularity()
val audioManager = getSystemService(Context.AUDIO_SERVICE) as? AudioManager
val audioSessionId = audioManager?.generateAudioSessionId()?.takeIf { it != 0 }
@@ -385,7 +469,7 @@ class FogwavePlaybackService : MediaLibraryService() {
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
)
mediaLibrarySession = MediaLibrarySession.Builder(this, player, librarySessionCallback)
mediaLibrarySession = MediaLibrarySession.Builder(this, StationSwitchingPlayer(player), librarySessionCallback)
.setSessionActivity(sessionActivity)
.build()
}
@@ -412,10 +496,13 @@ class FogwavePlaybackService : MediaLibraryService() {
override fun onGetSession(controllerInfo: MediaSession.ControllerInfo): MediaLibrarySession? = mediaLibrarySession
// Swiping the app away keeps only real playback alive (a short rebuffer counts): a failed
// stream, a pending reconnect or a pause stop the service. The Media3 default would also stop
// during a rebuffer, because isPlaying is false while buffering.
override fun onTaskRemoved(rootIntent: Intent?) {
if (!player.playWhenReady || player.mediaItemCount == 0) {
player.pause()
stopSelf()
val reconnecting = retryJob?.isActive == true || waitingForNetwork || player.playerError != null
if (!isPlaybackOngoing() || !player.playWhenReady || player.mediaItemCount == 0 || reconnecting) {
pauseAllPlayersAndStopSelf()
}
}
@@ -441,8 +528,6 @@ class FogwavePlaybackService : MediaLibraryService() {
companion object {
private const val ROOT_ID = "fogwave_root"
private const val TAG = "FogwavePlaybackService"
private const val MAX_RETRY_ATTEMPTS = 12
private const val MAX_PERMANENT_ERROR_RETRY_ATTEMPTS = 2
private const val RECONNECT_LOCK_TIMEOUT_MS = 2 * 60_000L
private const val LIVE_RESYNC_AFTER_MS = 30_000L
}
@@ -0,0 +1,45 @@
package cc.skysparkle.fogwave.player
import androidx.annotation.OptIn
import androidx.media3.common.PlaybackException
import androidx.media3.common.Player
import androidx.media3.common.util.UnstableApi
import androidx.media3.datasource.HttpDataSource
// Kept apart from the service and the UI controller so the decisions can be unit tested.
internal const val MAX_RETRY_ATTEMPTS = 12
internal const val MAX_PERMANENT_ERROR_RETRY_ATTEMPTS = 2
// A missing stream or an unsupported format will not fix itself, so it gets only a couple of
// attempts (a stale token or a short server outage can still recover); network errors get the full backoff.
@OptIn(UnstableApi::class)
internal fun maxRetryAttemptsFor(error: PlaybackException): Int {
val httpCode = (error.cause as? HttpDataSource.InvalidResponseCodeException)?.responseCode
val permanent = when (error.errorCode) {
PlaybackException.ERROR_CODE_IO_BAD_HTTP_STATUS ->
httpCode != null && httpCode in 400..499 && httpCode != 408 && httpCode != 429
PlaybackException.ERROR_CODE_IO_FILE_NOT_FOUND,
PlaybackException.ERROR_CODE_IO_CLEARTEXT_NOT_PERMITTED,
PlaybackException.ERROR_CODE_PARSING_CONTAINER_UNSUPPORTED,
PlaybackException.ERROR_CODE_PARSING_MANIFEST_UNSUPPORTED,
PlaybackException.ERROR_CODE_DECODING_FORMAT_UNSUPPORTED -> true
else -> false
}
return if (permanent) MAX_PERMANENT_ERROR_RETRY_ATTEMPTS else MAX_RETRY_ATTEMPTS
}
/** What the UI shows for the session's player; [errorMessage] turns a playback error into text. */
internal fun deriveState(p: Player, errorMessage: (PlaybackException) -> String): PlayerState {
p.playerError?.let { return PlayerState.Error(errorMessage(it)) }
return when (p.playbackState) {
Player.STATE_READY -> if (p.playWhenReady) PlayerState.Playing else PlayerState.Paused
Player.STATE_BUFFERING, Player.STATE_ENDED ->
if (p.playWhenReady) PlayerState.Connecting else PlayerState.Paused
else -> when {
p.mediaItemCount == 0 -> PlayerState.Idle
p.playWhenReady -> PlayerState.Connecting
else -> PlayerState.Paused
}
}
}
@@ -43,7 +43,7 @@ class RadioPlayerManager(private val context: Context) {
private val playerListener = object : Player.Listener {
override fun onEvents(player: Player, events: Player.Events) {
_playerState.value = deriveState(player)
_playerState.value = deriveState(player, ::errorMessage)
_currentMediaId.value = player.currentMediaItem?.mediaId
_nowPlayingTitle.value = streamTitle(player)
}
@@ -88,7 +88,7 @@ class RadioPlayerManager(private val context: Context) {
if (station != null) {
playStation(station)
} else {
_playerState.value = deriveState(c)
_playerState.value = deriveState(c, ::errorMessage)
_currentMediaId.value = c.currentMediaItem?.mediaId
_nowPlayingTitle.value = streamTitle(c)
}
@@ -117,20 +117,6 @@ class RadioPlayerManager(private val context: Context) {
controllerFuture = null
}
private fun deriveState(p: Player): PlayerState {
p.playerError?.let { return PlayerState.Error(errorMessage(it)) }
return when (p.playbackState) {
Player.STATE_READY -> if (p.playWhenReady) PlayerState.Playing else PlayerState.Paused
Player.STATE_BUFFERING, Player.STATE_ENDED ->
if (p.playWhenReady) PlayerState.Connecting else PlayerState.Paused
else -> when {
p.mediaItemCount == 0 -> PlayerState.Idle
p.playWhenReady -> PlayerState.Connecting
else -> PlayerState.Paused
}
}
}
// Stream metadata replaces the item's own title; the station name itself is not a song.
private fun streamTitle(p: Player): String? {
val title = p.mediaMetadata.title?.toString()?.trim()
@@ -139,9 +139,12 @@ class RadioViewModel(application: Application) : AndroidViewModel(application) {
viewModelScope.launch {
playerManager.currentMediaId.collect { id ->
if (id != null && id != _currentStation.value?.id) {
// Switched outside the app (notification, headset, Android Auto): count it like a tap.
stations.find { it.id == id }?.let { onAir ->
_currentStation.value = onAir
repository.setLastStationId(onAir.id)
repository.pushRecent(onAir.id)
repository.recordStationPlayed(onAir.id)
}
}
}
@@ -250,10 +253,6 @@ class RadioViewModel(application: Application) : AndroidViewModel(application) {
AudioEffectsController.setLoudnessEnabled(enabled)
}
fun setLoudnessGain(gainMillibel: Float) {
AudioEffectsController.setLoudnessGain(gainMillibel)
}
fun setDynamicsProcessingEnabled(enabled: Boolean) {
AudioEffectsController.setDynamicsProcessingEnabled(enabled)
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 998 B

-4
View File
@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<full-backup-content>
</full-backup-content>
@@ -1,7 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<data-extraction-rules>
<cloud-backup>
</cloud-backup>
</data-extraction-rules>