Compare commits

...

2 commits
dev ... tasker

Author SHA1 Message Date
Alexander Capehart
8094ff05d5
playback: stop gap that occurs between load/playback 2024-07-27 19:48:48 -06:00
Alexander Capehart
8bc7418887
tasker: kind of working plugin 2024-05-18 17:24:08 -06:00
12 changed files with 184 additions and 58 deletions

View file

@ -136,16 +136,14 @@
</receiver> </receiver>
<!-- Tasker integration -->
<activity <activity
android:name=".tasker.StartConfigBasicAction" android:name=".tasker.StartConfigBasicAction"
android:exported="true" android:exported="true"
android:icon="@mipmap/ic_launcher" android:icon="@mipmap/ic_launcher"
android:label="Start Auxio"> android:label="Start">
<intent-filter> <intent-filter>
<action android:name="com.twofortyfouram.locale.intent.action.EDIT_SETTING" /> <action android:name="com.twofortyfouram.locale.intent.action.EDIT_SETTING" />
</intent-filter> </intent-filter>
</activity> </activity>
</application> </application>
</manifest> </manifest>

View file

@ -28,8 +28,7 @@ import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject import javax.inject.Inject
import org.oxycblt.auxio.music.service.IndexerServiceFragment import org.oxycblt.auxio.music.service.IndexerServiceFragment
import org.oxycblt.auxio.playback.service.MediaSessionServiceFragment import org.oxycblt.auxio.playback.service.MediaSessionServiceFragment
import org.oxycblt.auxio.tasker.indicateServiceRunning import org.oxycblt.auxio.util.logD
import org.oxycblt.auxio.tasker.indicateServiceStopped
@AndroidEntryPoint @AndroidEntryPoint
class AuxioService : MediaLibraryService(), ForegroundListener { class AuxioService : MediaLibraryService(), ForegroundListener {
@ -37,16 +36,17 @@ class AuxioService : MediaLibraryService(), ForegroundListener {
@Inject lateinit var indexingFragment: IndexerServiceFragment @Inject lateinit var indexingFragment: IndexerServiceFragment
private var nativeStart = false
@SuppressLint("WrongConstant") @SuppressLint("WrongConstant")
override fun onCreate() { override fun onCreate() {
super.onCreate() super.onCreate()
mediaSessionFragment.attach(this, this) mediaSessionFragment.attach(this, this)
indexingFragment.attach(this) indexingFragment.attach(this)
indicateServiceRunning()
} }
override fun onBind(intent: Intent?): IBinder? { override fun onBind(intent: Intent?): IBinder? {
handleIntent(intent) // handleIntent(intent)
return super.onBind(intent) return super.onBind(intent)
} }
@ -58,7 +58,8 @@ class AuxioService : MediaLibraryService(), ForegroundListener {
} }
private fun handleIntent(intent: Intent?) { private fun handleIntent(intent: Intent?) {
val nativeStart = intent?.getBooleanExtra(INTENT_KEY_NATIVE_START, false) ?: false nativeStart = intent?.getBooleanExtra(INTENT_KEY_INTERNAL_START, false) ?: false
logD("${intent} $nativeStart")
if (!nativeStart) { if (!nativeStart) {
// Some foreign code started us, no guarantees about foreground stability. Figure // Some foreign code started us, no guarantees about foreground stability. Figure
// out what to do. // out what to do.
@ -73,7 +74,6 @@ class AuxioService : MediaLibraryService(), ForegroundListener {
override fun onDestroy() { override fun onDestroy() {
super.onDestroy() super.onDestroy()
indicateServiceStopped()
indexingFragment.release() indexingFragment.release()
mediaSessionFragment.release() mediaSessionFragment.release()
} }
@ -86,7 +86,9 @@ class AuxioService : MediaLibraryService(), ForegroundListener {
} }
override fun updateForeground(change: ForegroundListener.Change) { override fun updateForeground(change: ForegroundListener.Change) {
if (mediaSessionFragment.hasNotification()) { val state = mediaSessionFragment.hasNotification()
if (state == MediaSessionServiceFragment.NotificationState.RUNNING) {
if (change == ForegroundListener.Change.MEDIA_SESSION) { if (change == ForegroundListener.Change.MEDIA_SESSION) {
mediaSessionFragment.createNotification { mediaSessionFragment.createNotification {
startForeground(it.notificationId, it.notification) startForeground(it.notificationId, it.notification)
@ -98,7 +100,7 @@ class AuxioService : MediaLibraryService(), ForegroundListener {
indexingFragment.createNotification { indexingFragment.createNotification {
if (it != null) { if (it != null) {
startForeground(it.code, it.build()) startForeground(it.code, it.build())
} else { } else if (state == MediaSessionServiceFragment.NotificationState.NOT_RUNNING) {
ServiceCompat.stopForeground(this, ServiceCompat.STOP_FOREGROUND_REMOVE) ServiceCompat.stopForeground(this, ServiceCompat.STOP_FOREGROUND_REMOVE)
} }
} }
@ -107,7 +109,7 @@ class AuxioService : MediaLibraryService(), ForegroundListener {
companion object { companion object {
// This is only meant for Auxio to internally ensure that it's state management will work. // This is only meant for Auxio to internally ensure that it's state management will work.
const val INTENT_KEY_NATIVE_START = BuildConfig.APPLICATION_ID + ".service.NATIVE_START" const val INTENT_KEY_INTERNAL_START = BuildConfig.APPLICATION_ID + ".service.INTERNAL_START"
} }
} }

View file

@ -57,6 +57,7 @@ object IntegerTable {
const val PLAYBACK_NOTIFICATION_CODE = 0xA0A0 const val PLAYBACK_NOTIFICATION_CODE = 0xA0A0
/** "Music loading" notification code */ /** "Music loading" notification code */
const val INDEXER_NOTIFICATION_CODE = 0xA0A1 const val INDEXER_NOTIFICATION_CODE = 0xA0A1
const val TASKER_ERROR_NOT_RESTORED = 0xA0A2
/** MainActivity Intent request code */ /** MainActivity Intent request code */
const val REQUEST_CODE = 0xA0C0 const val REQUEST_CODE = 0xA0C0
/** RepeatMode.NONE */ /** RepeatMode.NONE */

View file

@ -71,11 +71,11 @@ class MainActivity : AppCompatActivity() {
startService( startService(
Intent(this, AuxioService::class.java) Intent(this, AuxioService::class.java)
.putExtra(AuxioService.INTENT_KEY_NATIVE_START, true)) .putExtra(AuxioService.INTENT_KEY_INTERNAL_START, true))
if (!startIntentAction(intent)) { if (!startIntentAction(intent)) {
// No intent action to do, just restore the previously saved state. // No intent action to do, just restore the previously saved state.
playbackModel.playDeferred(DeferredPlayback.RestoreState) playbackModel.playDeferred(DeferredPlayback.RestoreState(sessionRequired = false))
} }
} }

View file

@ -96,7 +96,9 @@ constructor(
// Not observing and done loading, exit foreground. // Not observing and done loading, exit foreground.
logD("Exiting foreground") logD("Exiting foreground")
post(observingNotification) post(observingNotification)
} else { } else if (!playbackManager.awaitingDeferredPlayback) {
// Very possible we are done loading music and now need to avoid downtime
// as the player begins to load the playback state.
post(null) post(null)
} }
} }

View file

@ -42,6 +42,7 @@ import kotlinx.coroutines.delay
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import kotlinx.coroutines.yield import kotlinx.coroutines.yield
import org.oxycblt.auxio.ForegroundListener
import org.oxycblt.auxio.image.ImageSettings import org.oxycblt.auxio.image.ImageSettings
import org.oxycblt.auxio.music.MusicParent import org.oxycblt.auxio.music.MusicParent
import org.oxycblt.auxio.music.MusicRepository import org.oxycblt.auxio.music.MusicRepository
@ -84,11 +85,13 @@ class ExoPlaybackStateHolder(
private val restoreScope = CoroutineScope(Dispatchers.IO + saveJob) private val restoreScope = CoroutineScope(Dispatchers.IO + saveJob)
private var currentSaveJob: Job? = null private var currentSaveJob: Job? = null
private var openAudioEffectSession = false private var openAudioEffectSession = false
private var foregroundListener: ForegroundListener? = null
var sessionOngoing = false override var sessionOngoing = false
private set private set
fun attach() { fun attach(foregroundListener: ForegroundListener) {
this.foregroundListener = foregroundListener
imageSettings.registerListener(this) imageSettings.registerListener(this)
player.addListener(this) player.addListener(this)
replayGainProcessor.attach() replayGainProcessor.attach()
@ -105,6 +108,7 @@ class ExoPlaybackStateHolder(
replayGainProcessor.release() replayGainProcessor.release()
imageSettings.unregisterListener(this) imageSettings.unregisterListener(this)
player.release() player.release()
foregroundListener = null
} }
override var parent: MusicParent? = null override var parent: MusicParent? = null
@ -157,16 +161,26 @@ class ExoPlaybackStateHolder(
musicRepository.deviceLibrary musicRepository.deviceLibrary
// No library, cannot do anything. // No library, cannot do anything.
?: return false ?: return false
logD((Exception().stackTraceToString()))
when (action) { when (action) {
// Restore state -> Start a new restoreState job // Restore state -> Start a new restoreState job
is DeferredPlayback.RestoreState -> { is DeferredPlayback.RestoreState -> {
logD("Restoring playback state") logD("Restoring playback state")
restoreScope.launch { restoreScope.launch {
persistenceRepository.readState()?.let { val state = persistenceRepository.readState()
if (state != null) {
// Apply the saved state on the main thread to prevent code expecting // Apply the saved state on the main thread to prevent code expecting
// state updates on the main thread from crashing. // state updates on the main thread from crashing.
withContext(Dispatchers.Main) { playbackManager.applySavedState(it, false) } withContext(Dispatchers.Main) {
playbackManager.applySavedState(state, false)
if (action.sessionRequired) {
sessionOngoing = true
foregroundListener?.updateForeground(ForegroundListener.Change.MEDIA_SESSION)
}
}
} else {
logD("No saved state to restore")
foregroundListener?.updateForeground(ForegroundListener.Change.MEDIA_SESSION)
} }
} }
} }
@ -181,11 +195,15 @@ class ExoPlaybackStateHolder(
// Open -> Try to find the Song for the given file and then play it from all songs // Open -> Try to find the Song for the given file and then play it from all songs
is DeferredPlayback.Open -> { is DeferredPlayback.Open -> {
logD("Opening specified file") logD("Opening specified file")
deviceLibrary.findSongForUri(context, action.uri)?.let { song -> val song = deviceLibrary.findSongForUri(context, action.uri)
if (song != null) {
playbackManager.play( playbackManager.play(
requireNotNull(commandFactory.song(song, ShuffleMode.IMPLICIT)) { requireNotNull(commandFactory.song(song, ShuffleMode.IMPLICIT)) {
"Invalid playback parameters" "Invalid playback parameters"
}) })
} else {
logD("No song found for uri")
foregroundListener?.updateForeground(ForegroundListener.Change.MEDIA_SESSION)
} }
} }
} }
@ -365,13 +383,36 @@ class ExoPlaybackStateHolder(
rawQueue: RawQueue, rawQueue: RawQueue,
ack: StateAck.NewPlayback? ack: StateAck.NewPlayback?
) { ) {
this.parent = parent var sendNewPlaybackEvent = false
player.setMediaItems(rawQueue.heap.map { it.toMediaItem(context, null) }) var shouldSeek = false
if (rawQueue.isShuffled) { if (this.parent != parent) {
player.shuffleModeEnabled = true this.parent = parent
player.setShuffleOrder(BetterShuffleOrder(rawQueue.shuffledMapping.toIntArray())) sendNewPlaybackEvent = true
} else { }
player.shuffleModeEnabled = false if (rawQueue != resolveQueue()) {
player.setMediaItems(rawQueue.heap.map { it.toMediaItem(context, null) })
if (rawQueue.isShuffled) {
player.shuffleModeEnabled = true
player.setShuffleOrder(BetterShuffleOrder(rawQueue.shuffledMapping.toIntArray()))
} else {
player.shuffleModeEnabled = false
}
player.seekTo(rawQueue.heapIndex, C.TIME_UNSET)
player.prepare()
player.pause()
sendNewPlaybackEvent = true
shouldSeek = true
}
repeatMode(repeatMode)
// Positions in milliseconds will drift during tight restores (i.e what the music loader
// does to sanitize the state), compare by seconds instead.
// if (positionMs.msToSecs() != player.currentPosition.msToSecs() || shouldSeek) {
// player.seekTo(positionMs)
// }
if (sendNewPlaybackEvent) {
ack?.let { playbackManager.ack(this, it) }
} }
player.seekTo(rawQueue.heapIndex, C.TIME_UNSET) player.seekTo(rawQueue.heapIndex, C.TIME_UNSET)
player.prepare() player.prepare()

View file

@ -51,7 +51,6 @@ import org.oxycblt.auxio.R
import org.oxycblt.auxio.music.service.MediaItemBrowser import org.oxycblt.auxio.music.service.MediaItemBrowser
import org.oxycblt.auxio.playback.state.DeferredPlayback import org.oxycblt.auxio.playback.state.DeferredPlayback
import org.oxycblt.auxio.playback.state.PlaybackStateManager import org.oxycblt.auxio.playback.state.PlaybackStateManager
import org.oxycblt.auxio.util.logD
import org.oxycblt.auxio.util.newMainPendingIntent import org.oxycblt.auxio.util.newMainPendingIntent
class MediaSessionServiceFragment class MediaSessionServiceFragment
@ -112,11 +111,25 @@ constructor(
fun handleNonNativeStart() { fun handleNonNativeStart() {
// At minimum we want to ensure an active playback state. // At minimum we want to ensure an active playback state.
// TODO: Possibly also force to go foreground? // TODO: Possibly also force to go foreground?
logD("Handling non-native start.") // We assume that all non-native starts are from media controllers that should know
playbackManager.playDeferred(DeferredPlayback.RestoreState) // what they are doing and have their own commands they want to execute.
playbackManager.playDeferred(DeferredPlayback.RestoreState(sessionRequired = true))
} }
fun hasNotification(): Boolean = exoHolder.sessionOngoing enum class NotificationState {
RUNNING,
NOT_RUNNING,
MAYBE_LATER
}
fun hasNotification(): NotificationState =
if (exoHolder.sessionOngoing) {
NotificationState.RUNNING
} else if (playbackManager.hasDeferredPlayback()) {
NotificationState.MAYBE_LATER
} else {
NotificationState.NOT_RUNNING
}
fun createNotification(post: (MediaNotification) -> Unit) { fun createNotification(post: (MediaNotification) -> Unit) {
val notification = val notification =

View file

@ -41,6 +41,9 @@ interface PlaybackStateHolder {
/** The current [MusicParent] being played from. Null if playing from all songs. */ /** The current [MusicParent] being played from. Null if playing from all songs. */
val parent: MusicParent? val parent: MusicParent?
/** Whether the player is in an active playback session. */
val sessionOngoing: Boolean
/** /**
* Resolve the current queue state as a [RawQueue]. * Resolve the current queue state as a [RawQueue].
* *
@ -275,8 +278,12 @@ data class QueueChange(val type: Type, val instructions: UpdateInstructions) {
/** Possible long-running background tasks handled by the background playback task. */ /** Possible long-running background tasks handled by the background playback task. */
sealed interface DeferredPlayback { sealed interface DeferredPlayback {
/** Restore the previously saved playback state. */ /**
data object RestoreState : DeferredPlayback * Restore the previously saved playback state.
*
* @param sessionRequired Whether a playback session must be started after restoration.
*/
data class RestoreState(val sessionRequired: Boolean) : DeferredPlayback
/** /**
* Start shuffled playback of the entire music library. Analogous to the "Shuffle All" shortcut. * Start shuffled playback of the entire music library. Analogous to the "Shuffle All" shortcut.

View file

@ -66,6 +66,13 @@ interface PlaybackStateManager {
/** Whether the queue is shuffled or not. */ /** Whether the queue is shuffled or not. */
val isShuffled: Boolean val isShuffled: Boolean
/** Whether there is an ongoing playback session or not. */
val sessionOngoing: Boolean
/* Whether the player is awaiting a [DeferredPlayback] to be consumed. */
val awaitingDeferredPlayback: Boolean
/** The audio session ID of the internal player. Null if no internal player exists. */ /** The audio session ID of the internal player. Null if no internal player exists. */
val currentAudioSessionId: Int? val currentAudioSessionId: Int?
@ -195,6 +202,13 @@ interface PlaybackStateManager {
*/ */
fun ack(stateHolder: PlaybackStateHolder, ack: StateAck) fun ack(stateHolder: PlaybackStateHolder, ack: StateAck)
/**
* Check if there is a pending [DeferredPlayback] to handle.
*
* @return Whether there is a pending [DeferredPlayback] to handle.
*/
fun hasDeferredPlayback(): Boolean
/** /**
* Start a [DeferredPlayback] for the current [PlaybackStateHolder] to handle eventually. * Start a [DeferredPlayback] for the current [PlaybackStateHolder] to handle eventually.
* *
@ -382,6 +396,13 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
override val isShuffled override val isShuffled
get() = stateMirror.isShuffled get() = stateMirror.isShuffled
override val sessionOngoing
get() = stateHolder?.sessionOngoing ?: false
override val awaitingDeferredPlayback: Boolean
get() = pendingDeferredPlayback != null
override val currentAudioSessionId: Int? override val currentAudioSessionId: Int?
get() = stateHolder?.audioSessionId get() = stateHolder?.audioSessionId
@ -522,6 +543,8 @@ class PlaybackStateManagerImpl @Inject constructor() : PlaybackStateManager {
// --- INTERNAL PLAYER FUNCTIONS --- // --- INTERNAL PLAYER FUNCTIONS ---
@Synchronized override fun hasDeferredPlayback(): Boolean = pendingDeferredPlayback != null
@Synchronized @Synchronized
override fun playDeferred(action: DeferredPlayback) { override fun playDeferred(action: DeferredPlayback) {
val stateHolder = stateHolder val stateHolder = stateHolder

View file

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package org.oxycblt.auxio.tasker package org.oxycblt.auxio.tasker
import android.app.Activity import android.app.Activity
@ -29,29 +29,21 @@ import com.joaomgcd.taskerpluginlibrary.config.TaskerPluginConfigHelperNoOutputO
import com.joaomgcd.taskerpluginlibrary.config.TaskerPluginConfigNoInput import com.joaomgcd.taskerpluginlibrary.config.TaskerPluginConfigNoInput
import com.joaomgcd.taskerpluginlibrary.input.TaskerInput import com.joaomgcd.taskerpluginlibrary.input.TaskerInput
import com.joaomgcd.taskerpluginlibrary.runner.TaskerPluginResult import com.joaomgcd.taskerpluginlibrary.runner.TaskerPluginResult
import com.joaomgcd.taskerpluginlibrary.runner.TaskerPluginResultError
import com.joaomgcd.taskerpluginlibrary.runner.TaskerPluginResultSucess import com.joaomgcd.taskerpluginlibrary.runner.TaskerPluginResultSucess
import dagger.hilt.EntryPoints
import kotlinx.coroutines.runBlocking
import org.oxycblt.auxio.AuxioService import org.oxycblt.auxio.AuxioService
import org.oxycblt.auxio.IntegerTable
import org.oxycblt.auxio.playback.state.DeferredPlayback
private var serviceRunning = false class StartHelper(config: TaskerPluginConfig<Unit>) :
TaskerPluginConfigHelperNoOutputOrInput<StartStateRunner>(config) {
fun indicateServiceRunning() { override val runnerClass: Class<StartStateRunner>
serviceRunning = true get() = StartStateRunner::class.java
}
fun indicateServiceStopped() {
serviceRunning = false
}
class StartActionHelper(config: TaskerPluginConfig<Unit>) :
TaskerPluginConfigHelperNoOutputOrInput<StartActionRunner>(config) {
override val runnerClass: Class<StartActionRunner>
get() = StartActionRunner::class.java
override fun addToStringBlurb(input: TaskerInput<Unit>, blurbBuilder: StringBuilder) { override fun addToStringBlurb(input: TaskerInput<Unit>, blurbBuilder: StringBuilder) {
blurbBuilder.append( blurbBuilder.append("Shuffles All Songs Once the Service is Available")
"Starts the Auxio Service. This will block until the service is fully initialized." +
"You must start active playback/foreground state after this or Auxio may" +
"crash.")
} }
} }
@ -59,7 +51,7 @@ class StartConfigBasicAction : Activity(), TaskerPluginConfigNoInput {
override val context: Context override val context: Context
get() = applicationContext get() = applicationContext
private val taskerHelper by lazy { StartActionHelper(this) } private val taskerHelper by lazy { StartHelper(this) }
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
@ -67,10 +59,27 @@ class StartConfigBasicAction : Activity(), TaskerPluginConfigNoInput {
} }
} }
class StartActionRunner : TaskerPluginRunnerActionNoOutputOrInput() { class StartStateRunner : TaskerPluginRunnerActionNoOutputOrInput() {
override fun run(context: Context, input: TaskerInput<Unit>): TaskerPluginResult<Unit> { override fun run(context: Context, input: TaskerInput<Unit>): TaskerPluginResult<Unit> {
ContextCompat.startForegroundService(context, Intent(context, AuxioService::class.java)) ContextCompat.startForegroundService(
while (!serviceRunning) {} context,
Intent(context, AuxioService::class.java)
.putExtra(AuxioService.INTENT_KEY_INTERNAL_START, true)
)
val entryPoint = EntryPoints.get(context.applicationContext, TaskerEntryPoint::class.java)
val playbackManager = entryPoint.playbackManager()
runBlocking {
playbackManager.playDeferred(DeferredPlayback.RestoreState(sessionRequired = true))
}
while (!playbackManager.sessionOngoing) {
if (!playbackManager.awaitingDeferredPlayback) {
return TaskerPluginResultError(
IntegerTable.TASKER_ERROR_NOT_RESTORED,
"No state to restore, did not restart playback."
)
}
}
Thread.sleep(100)
return TaskerPluginResultSucess() return TaskerPluginResultSucess()
} }
} }

View file

@ -0,0 +1,30 @@
/*
* Copyright (c) 2024 Auxio Project
* TaskerEntryPoint.kt is part of Auxio.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.oxycblt.auxio.tasker
import dagger.hilt.EntryPoint
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import org.oxycblt.auxio.playback.state.PlaybackStateManager
@EntryPoint
@InstallIn(SingletonComponent::class)
interface TaskerEntryPoint {
fun playbackManager(): PlaybackStateManager
}

2
media

@ -1 +1 @@
Subproject commit 00124cbac493c06a24e19b01893946bdaf8faf58 Subproject commit 9fc2401b8fdc2b23905402462e775c6db4e1527f