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
@@ -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,32 +146,96 @@ 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
}
}.toMutableList()
resolved.firstOrNull()?.let { item ->
Log.d(TAG, "MediaItem resolved: mediaId=${item.mediaId} uri=${item.localConfiguration?.uri}")
lastRequestedItem = item
retryJob?.cancel()
retryAttempt = 0
}
val resolved = mediaItems.map { resolveStation(it).toMediaItem(this@FogwavePlaybackService) }
.toMutableList()
resolved.firstOrNull()?.let { onNewRequest(it) }
return Futures.immediateFuture(resolved)
}
}
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
}
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 {
override fun onPlaybackStateChanged(playbackState: Int) {
val stateName = when (playbackState) {
@@ -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
}