mirror of
https://github.com/kalarina-bit/Fogwave.git
synced 2026-11-22 08:06:09 +00:00
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:
@@ -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()
|
refresh()
|
||||||
}
|
}
|
||||||
|
|
||||||
fun setLoudnessGain(gainMillibel: Float) {
|
|
||||||
engine?.setLoudnessGain(gainMillibel)
|
|
||||||
refresh()
|
|
||||||
}
|
|
||||||
|
|
||||||
fun setDynamicsProcessingEnabled(enabled: Boolean) {
|
fun setDynamicsProcessingEnabled(enabled: Boolean) {
|
||||||
engine?.setDynamicsProcessingEnabled(enabled)
|
engine?.setDynamicsProcessingEnabled(enabled)
|
||||||
refresh()
|
refresh()
|
||||||
|
|||||||
@@ -25,8 +25,6 @@ data class AudioEffectsState(
|
|||||||
val currentPreset: Int = -1,
|
val currentPreset: Int = -1,
|
||||||
val loudnessAvailable: Boolean = false,
|
val loudnessAvailable: Boolean = false,
|
||||||
val loudnessEnabled: Boolean = false,
|
val loudnessEnabled: Boolean = false,
|
||||||
val loudnessGainMillibel: Float = 0f,
|
|
||||||
val loudnessMaxGainMillibel: Float = 2000f,
|
|
||||||
val dynamicsProcessingAvailable: Boolean = false,
|
val dynamicsProcessingAvailable: Boolean = false,
|
||||||
val dynamicsProcessingEnabled: 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 equalizerEnabled = prefs.getBoolean(KEY_EQ_ENABLED, false)
|
||||||
private var loudnessEnabled = prefs.getBoolean(KEY_LOUDNESS_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)
|
private var dynamicsEnabled = prefs.getBoolean(KEY_DYNAMICS_ENABLED, false)
|
||||||
|
|
||||||
init {
|
init {
|
||||||
@@ -178,7 +179,6 @@ class AudioEffectsEngine(context: Context, audioSessionId: Int) {
|
|||||||
currentPreset = if (eqAvailable) currentPresetIndex else -1,
|
currentPreset = if (eqAvailable) currentPresetIndex else -1,
|
||||||
loudnessAvailable = loudnessEnhancer != null,
|
loudnessAvailable = loudnessEnhancer != null,
|
||||||
loudnessEnabled = loudnessEnhancer != null && loudnessEnabled,
|
loudnessEnabled = loudnessEnhancer != null && loudnessEnabled,
|
||||||
loudnessGainMillibel = if (loudnessEnhancer != null) loudnessGain.toFloat() else 0f,
|
|
||||||
dynamicsProcessingAvailable = dynamicsProcessing != null,
|
dynamicsProcessingAvailable = dynamicsProcessing != null,
|
||||||
dynamicsProcessingEnabled = dynamicsProcessing != null && dynamicsEnabled
|
dynamicsProcessingEnabled = dynamicsProcessing != null && dynamicsEnabled
|
||||||
)
|
)
|
||||||
@@ -233,17 +233,6 @@ class AudioEffectsEngine(context: Context, audioSessionId: Int) {
|
|||||||
} catch (_: Exception) {}
|
} 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) {
|
fun setDynamicsProcessingEnabled(enabled: Boolean) {
|
||||||
val dp = dynamicsProcessing ?: return
|
val dp = dynamicsProcessing ?: return
|
||||||
try {
|
try {
|
||||||
@@ -265,6 +254,7 @@ class AudioEffectsEngine(context: Context, audioSessionId: Int) {
|
|||||||
private companion object {
|
private companion object {
|
||||||
const val TAG = "AudioEffectsEngine"
|
const val TAG = "AudioEffectsEngine"
|
||||||
const val MAX_LOUDNESS_GAIN = 2000
|
const val MAX_LOUDNESS_GAIN = 2000
|
||||||
|
const val DEFAULT_LOUDNESS_GAIN = 600
|
||||||
const val KEY_EQ_ENABLED = "eq_enabled"
|
const val KEY_EQ_ENABLED = "eq_enabled"
|
||||||
const val KEY_PRESET = "eq_preset"
|
const val KEY_PRESET = "eq_preset"
|
||||||
const val KEY_BAND_PREFIX = "eq_band_"
|
const val KEY_BAND_PREFIX = "eq_band_"
|
||||||
|
|||||||
@@ -15,13 +15,13 @@ import android.util.Log
|
|||||||
import androidx.annotation.OptIn
|
import androidx.annotation.OptIn
|
||||||
import androidx.media3.common.AudioAttributes
|
import androidx.media3.common.AudioAttributes
|
||||||
import androidx.media3.common.C
|
import androidx.media3.common.C
|
||||||
|
import androidx.media3.common.ForwardingSimpleBasePlayer
|
||||||
import androidx.media3.common.MediaItem
|
import androidx.media3.common.MediaItem
|
||||||
import androidx.media3.common.MediaMetadata
|
import androidx.media3.common.MediaMetadata
|
||||||
import androidx.media3.common.PlaybackException
|
import androidx.media3.common.PlaybackException
|
||||||
import androidx.media3.common.Player
|
import androidx.media3.common.Player
|
||||||
import androidx.media3.common.util.UnstableApi
|
import androidx.media3.common.util.UnstableApi
|
||||||
import androidx.media3.datasource.DefaultHttpDataSource
|
import androidx.media3.datasource.DefaultHttpDataSource
|
||||||
import androidx.media3.datasource.HttpDataSource
|
|
||||||
import androidx.media3.exoplayer.DefaultLoadControl
|
import androidx.media3.exoplayer.DefaultLoadControl
|
||||||
import androidx.media3.exoplayer.ExoPlayer
|
import androidx.media3.exoplayer.ExoPlayer
|
||||||
import androidx.media3.exoplayer.source.DefaultMediaSourceFactory
|
import androidx.media3.exoplayer.source.DefaultMediaSourceFactory
|
||||||
@@ -33,6 +33,7 @@ import androidx.media3.session.MediaSession
|
|||||||
import cc.skysparkle.fogwave.BuildConfig
|
import cc.skysparkle.fogwave.BuildConfig
|
||||||
import cc.skysparkle.fogwave.MainActivity
|
import cc.skysparkle.fogwave.MainActivity
|
||||||
import cc.skysparkle.fogwave.R
|
import cc.skysparkle.fogwave.R
|
||||||
|
import cc.skysparkle.fogwave.data.model.RadioStation
|
||||||
import cc.skysparkle.fogwave.data.repository.RadioRepository
|
import cc.skysparkle.fogwave.data.repository.RadioRepository
|
||||||
import com.google.common.collect.ImmutableList
|
import com.google.common.collect.ImmutableList
|
||||||
import com.google.common.util.concurrent.Futures
|
import com.google.common.util.concurrent.Futures
|
||||||
@@ -50,6 +51,10 @@ class FogwavePlaybackService : MediaLibraryService() {
|
|||||||
private var mediaLibrarySession: MediaLibrarySession? = null
|
private var mediaLibrarySession: MediaLibrarySession? = null
|
||||||
private lateinit var repository: RadioRepository
|
private lateinit var repository: RadioRepository
|
||||||
private lateinit var player: ExoPlayer
|
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 var audioEffectsEngine: AudioEffectsEngine? = null
|
||||||
|
|
||||||
private val serviceScope = CoroutineScope(Dispatchers.Main.immediate + SupervisorJob())
|
private val serviceScope = CoroutineScope(Dispatchers.Main.immediate + SupervisorJob())
|
||||||
@@ -66,6 +71,11 @@ class FogwavePlaybackService : MediaLibraryService() {
|
|||||||
private var connectivityManager: ConnectivityManager? = null
|
private var connectivityManager: ConnectivityManager? = null
|
||||||
private var networkCallback: ConnectivityManager.NetworkCallback? = null
|
private var networkCallback: ConnectivityManager.NetworkCallback? = null
|
||||||
private var defaultNetwork: Network? = 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
|
// 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.
|
// 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))
|
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(
|
override fun onAddMediaItems(
|
||||||
mediaSession: MediaSession,
|
mediaSession: MediaSession,
|
||||||
controller: MediaSession.ControllerInfo,
|
controller: MediaSession.ControllerInfo,
|
||||||
mediaItems: MutableList<MediaItem>
|
mediaItems: MutableList<MediaItem>
|
||||||
): ListenableFuture<MutableList<MediaItem>> {
|
): ListenableFuture<MutableList<MediaItem>> {
|
||||||
val resolved = mediaItems.map { item ->
|
val resolved = mediaItems.map { resolveStation(it).toMediaItem(this@FogwavePlaybackService) }
|
||||||
if (item.localConfiguration != null) {
|
.toMutableList()
|
||||||
item
|
resolved.firstOrNull()?.let { onNewRequest(it) }
|
||||||
} else {
|
return Futures.immediateFuture(resolved)
|
||||||
repository.stations.find { it.id == item.mediaId }
|
}
|
||||||
?.toMediaItem(this@FogwavePlaybackService)
|
|
||||||
?: item
|
|
||||||
}
|
}
|
||||||
}.toMutableList()
|
|
||||||
|
|
||||||
resolved.firstOrNull()?.let { item ->
|
private fun resolveStation(item: MediaItem): RadioStation {
|
||||||
Log.d(TAG, "MediaItem resolved: mediaId=${item.mediaId} uri=${item.localConfiguration?.uri}")
|
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
|
lastRequestedItem = item
|
||||||
retryJob?.cancel()
|
retryJob?.cancel()
|
||||||
retryAttempt = 0
|
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 {
|
private val resiliencePlayerListener = object : Player.Listener {
|
||||||
@@ -196,6 +270,7 @@ class FogwavePlaybackService : MediaLibraryService() {
|
|||||||
Log.d(TAG, "Reconnect cancelled - playWhenReady=false (reason=$reason)")
|
Log.d(TAG, "Reconnect cancelled - playWhenReady=false (reason=$reason)")
|
||||||
}
|
}
|
||||||
retryJob?.cancel()
|
retryJob?.cancel()
|
||||||
|
waitingForNetwork = false
|
||||||
releaseReconnectLocks()
|
releaseReconnectLocks()
|
||||||
pausedAtMs = SystemClock.elapsedRealtime()
|
pausedAtMs = SystemClock.elapsedRealtime()
|
||||||
return
|
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) {
|
private fun scheduleReconnect(immediate: Boolean = false, maxAttempts: Int = MAX_RETRY_ATTEMPTS) {
|
||||||
retryJob?.cancel()
|
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) {
|
if (!immediate && retryAttempt >= maxAttempts) {
|
||||||
// Give up instead of keeping the device busy forever; the error stays visible and a tap
|
// Give up instead of keeping the device busy forever; the error stays visible and a tap
|
||||||
// on play starts over.
|
// on play starts over.
|
||||||
@@ -316,13 +382,23 @@ class FogwavePlaybackService : MediaLibraryService() {
|
|||||||
private fun registerNetworkCallback() {
|
private fun registerNetworkCallback() {
|
||||||
val cm = getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager ?: return
|
val cm = getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager ?: return
|
||||||
connectivityManager = cm
|
connectivityManager = cm
|
||||||
|
hasNetwork = cm.activeNetwork != null
|
||||||
val callback = object : ConnectivityManager.NetworkCallback() {
|
val callback = object : ConnectivityManager.NetworkCallback() {
|
||||||
// Called on a ConnectivityManager thread; ExoPlayer must only be accessed on the main thread.
|
// Called on a ConnectivityManager thread; ExoPlayer must only be accessed on the main thread.
|
||||||
override fun onAvailable(network: Network) {
|
override fun onAvailable(network: Network) {
|
||||||
serviceScope.launch {
|
serviceScope.launch {
|
||||||
val previous = defaultNetwork
|
val previous = defaultNetwork
|
||||||
defaultNetwork = network
|
defaultNetwork = network
|
||||||
|
hasNetwork = true
|
||||||
|
val wasWaiting = waitingForNetwork
|
||||||
|
waitingForNetwork = false
|
||||||
if (!player.playWhenReady || player.playbackState == Player.STATE_READY) return@launch
|
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
|
// 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.
|
// the read timeout, so reopen right away instead of waiting for the error.
|
||||||
val switchedWhileStalled = previous != null && previous != network &&
|
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
|
networkCallback = callback
|
||||||
try {
|
try {
|
||||||
@@ -344,6 +427,7 @@ class FogwavePlaybackService : MediaLibraryService() {
|
|||||||
override fun onCreate() {
|
override fun onCreate() {
|
||||||
super.onCreate()
|
super.onCreate()
|
||||||
repository = RadioRepository(applicationContext)
|
repository = RadioRepository(applicationContext)
|
||||||
|
stationOrder = repository.stationsSortedByPopularity()
|
||||||
|
|
||||||
val audioManager = getSystemService(Context.AUDIO_SERVICE) as? AudioManager
|
val audioManager = getSystemService(Context.AUDIO_SERVICE) as? AudioManager
|
||||||
val audioSessionId = audioManager?.generateAudioSessionId()?.takeIf { it != 0 }
|
val audioSessionId = audioManager?.generateAudioSessionId()?.takeIf { it != 0 }
|
||||||
@@ -385,7 +469,7 @@ class FogwavePlaybackService : MediaLibraryService() {
|
|||||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
|
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
|
||||||
)
|
)
|
||||||
|
|
||||||
mediaLibrarySession = MediaLibrarySession.Builder(this, player, librarySessionCallback)
|
mediaLibrarySession = MediaLibrarySession.Builder(this, StationSwitchingPlayer(player), librarySessionCallback)
|
||||||
.setSessionActivity(sessionActivity)
|
.setSessionActivity(sessionActivity)
|
||||||
.build()
|
.build()
|
||||||
}
|
}
|
||||||
@@ -412,10 +496,13 @@ class FogwavePlaybackService : MediaLibraryService() {
|
|||||||
|
|
||||||
override fun onGetSession(controllerInfo: MediaSession.ControllerInfo): MediaLibrarySession? = mediaLibrarySession
|
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?) {
|
override fun onTaskRemoved(rootIntent: Intent?) {
|
||||||
if (!player.playWhenReady || player.mediaItemCount == 0) {
|
val reconnecting = retryJob?.isActive == true || waitingForNetwork || player.playerError != null
|
||||||
player.pause()
|
if (!isPlaybackOngoing() || !player.playWhenReady || player.mediaItemCount == 0 || reconnecting) {
|
||||||
stopSelf()
|
pauseAllPlayersAndStopSelf()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -441,8 +528,6 @@ class FogwavePlaybackService : MediaLibraryService() {
|
|||||||
companion object {
|
companion object {
|
||||||
private const val ROOT_ID = "fogwave_root"
|
private const val ROOT_ID = "fogwave_root"
|
||||||
private const val TAG = "FogwavePlaybackService"
|
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 RECONNECT_LOCK_TIMEOUT_MS = 2 * 60_000L
|
||||||
private const val LIVE_RESYNC_AFTER_MS = 30_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 {
|
private val playerListener = object : Player.Listener {
|
||||||
override fun onEvents(player: Player, events: Player.Events) {
|
override fun onEvents(player: Player, events: Player.Events) {
|
||||||
_playerState.value = deriveState(player)
|
_playerState.value = deriveState(player, ::errorMessage)
|
||||||
_currentMediaId.value = player.currentMediaItem?.mediaId
|
_currentMediaId.value = player.currentMediaItem?.mediaId
|
||||||
_nowPlayingTitle.value = streamTitle(player)
|
_nowPlayingTitle.value = streamTitle(player)
|
||||||
}
|
}
|
||||||
@@ -88,7 +88,7 @@ class RadioPlayerManager(private val context: Context) {
|
|||||||
if (station != null) {
|
if (station != null) {
|
||||||
playStation(station)
|
playStation(station)
|
||||||
} else {
|
} else {
|
||||||
_playerState.value = deriveState(c)
|
_playerState.value = deriveState(c, ::errorMessage)
|
||||||
_currentMediaId.value = c.currentMediaItem?.mediaId
|
_currentMediaId.value = c.currentMediaItem?.mediaId
|
||||||
_nowPlayingTitle.value = streamTitle(c)
|
_nowPlayingTitle.value = streamTitle(c)
|
||||||
}
|
}
|
||||||
@@ -117,20 +117,6 @@ class RadioPlayerManager(private val context: Context) {
|
|||||||
controllerFuture = null
|
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.
|
// Stream metadata replaces the item's own title; the station name itself is not a song.
|
||||||
private fun streamTitle(p: Player): String? {
|
private fun streamTitle(p: Player): String? {
|
||||||
val title = p.mediaMetadata.title?.toString()?.trim()
|
val title = p.mediaMetadata.title?.toString()?.trim()
|
||||||
|
|||||||
@@ -139,9 +139,12 @@ class RadioViewModel(application: Application) : AndroidViewModel(application) {
|
|||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
playerManager.currentMediaId.collect { id ->
|
playerManager.currentMediaId.collect { id ->
|
||||||
if (id != null && id != _currentStation.value?.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 ->
|
stations.find { it.id == id }?.let { onAir ->
|
||||||
_currentStation.value = onAir
|
_currentStation.value = onAir
|
||||||
repository.setLastStationId(onAir.id)
|
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)
|
AudioEffectsController.setLoudnessEnabled(enabled)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun setLoudnessGain(gainMillibel: Float) {
|
|
||||||
AudioEffectsController.setLoudnessGain(gainMillibel)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun setDynamicsProcessingEnabled(enabled: Boolean) {
|
fun setDynamicsProcessingEnabled(enabled: Boolean) {
|
||||||
AudioEffectsController.setDynamicsProcessingEnabled(enabled)
|
AudioEffectsController.setDynamicsProcessingEnabled(enabled)
|
||||||
}
|
}
|
||||||
|
|||||||
Binary file not shown.
|
Before Width: | Height: | Size: 998 B |
@@ -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>
|
|
||||||
Reference in New Issue
Block a user